예제 #1
0
        /**
         * Refresh access token.
         */
        public async Task <APIGatewayProxyResponse> RefreshAccessToken(IDataStores dataStores,
                                                                       IDictionary <string, string> requestHeaders,
                                                                       JObject requestBody)
        {
            Debug.Untested();
            Debug.AssertValid(dataStores);
            Debug.AssertValid(requestHeaders);
            Debug.AssertValid(requestBody);

            try {
                // Log call
                LoggingHelper.LogMessage($"UserIdentityService::RefreshAccessToken()");

                // Get the NoSQL DB client
                AmazonDynamoDBClient dbClient = (AmazonDynamoDBClient)dataStores.GetNoSQLDataStore().GetDBClient();
                Debug.AssertValid(dbClient);

                // Check inputs
                APIHelper.CheckEmptyRequestBody(requestBody);

                // Check authenticated endpoint security
                string loggedInUserId = await APIHelper.CheckLoggedIn(dbClient, requestHeaders);

                Debug.AssertID(loggedInUserId);

                // Perform logic
                DateTime?expiryTime = await UserIdentityService_RefreshAccessToken_LogicLayer.RefreshAccessToken(dbClient, loggedInUserId);

                Debug.AssertValid(expiryTime);

                // Respond
                RefreshAccessTokenResponse response = new RefreshAccessTokenResponse {
                    expiryTime = APIHelper.APIDateTimeStringFromDateTime(expiryTime)
                };
                return(new APIGatewayProxyResponse {
                    StatusCode = APIHelper.STATUS_CODE_OK,
                    Body = JsonConvert.SerializeObject(response)
                });
                //??--return Ok(response);
            } catch (Exception exception) {
                Debug.Tested();
                if (exception.Message == IdentityServiceLogicLayer.ERROR_CANNOT_EXTEND_ACCESS_TOKEN)
                {
                    Debug.Untested();
                    return(new APIGatewayProxyResponse {
                        StatusCode = APIHelper.STATUS_CODE_FORBIDDEN,
                        Body = $"{{ error = {IdentityServiceLogicLayer.CANNOT_EXTEND_ACCESS_TOKEN} }}"
                    });
                    //??--return StatusCode(APIHelper.STATUS_CODE_FORBIDDEN, new GeneralErrorResponse { error = IdentityServiceLogicLayer.CANNOT_EXTEND_ACCESS_TOKEN });
                }
                else
                {
                    Debug.Tested();
                    return(APIHelper.ResponseFromException(exception));
                }
            }
        }
예제 #2
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);
        }
예제 #3
0
        /**
         * Add a access token record to the data store.
         */
        internal static async Task AddAccessToken(AmazonDynamoDBClient dbClient, AccessToken accessToken)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(accessToken);
            Debug.AssertID(accessToken.ID);

            Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();

            item.Add(FIELD_ACCESS_TOKENS_ID, new AttributeValue(accessToken.ID));
            item.Add(FIELD_ACCESS_TOKENS_USER_ID, new AttributeValue(accessToken.UserID));
            item.Add(FIELD_ACCESS_TOKENS_EXPIRES, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(accessToken.Expires)));
            item.Add(FIELD_ACCESS_TOKENS_MAX_EXPIRY, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(accessToken.MaxExpiry)));
            PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_ACCESS_TOKENS, item);

            Debug.AssertValid(putResponse);
            //??++Check response?
        }
예제 #4
0
        /**
         * Add a link record to the data store.
         */
        internal static async Task AddLink(AmazonDynamoDBClient dbClient, Link link)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(link);
            Debug.AssertID(link.ID);

            Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();

            item.Add(FIELD_LINKS_ID, new AttributeValue(link.ID));
            item.Add(FIELD_LINKS_TYPE, new AttributeValue(link.Type));
            item.Add(FIELD_LINKS_EXPIRES, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(link.Expires)));
            item.Add(FIELD_LINKS_USER_ID, new AttributeValue(link.UserID));
            item.Add(FIELD_LINKS_REVOKED, new AttributeValue {
                BOOL = link.Revoked
            });
            item.Add(FIELD_LINKS_ONE_TIME_PASSWORD, new AttributeValue(link.OneTimePassword));
            PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_LINKS, item);

            Debug.AssertValid(putResponse);
            //??++Check response?
        }
        /**
         * Check validity of set user limits request inputs.
         */
        public static SetUserLimitsRequest CheckValidSetUserLimitsRequest(JObject requestBody)
        {
            Debug.Tested();
            Debug.AssertValidOrNull(requestBody);

            string error = null;

            if (requestBody != null)
            {
                bool   validMaxDailySpendingAmount = false;
                UInt32?maxDailySpendingAmount      = null;
                if (!APIHelper.RequestBodyContainsField(requestBody, "maxDailySpendingAmount", out JToken maxDailySpendingAmountField) || (maxDailySpendingAmountField.Type == JTokenType.Null))
                {
                    validMaxDailySpendingAmount = true;
                }
                else if (maxDailySpendingAmountField.Type == JTokenType.Integer)
                {
                    validMaxDailySpendingAmount = true;
                    maxDailySpendingAmount      = (UInt32)maxDailySpendingAmountField;
                }
                if (validMaxDailySpendingAmount)
                {
                    bool   validMaxTimeLoggedIn = false;
                    UInt64?maxTimeLoggedIn      = null;
                    if (!APIHelper.RequestBodyContainsField(requestBody, "maxTimeLoggedIn", out JToken maxTimeLoggedInField) || (maxTimeLoggedInField.Type == JTokenType.Null))
                    {
                        validMaxTimeLoggedIn = true;
                    }
                    else if (maxTimeLoggedInField.Type == JTokenType.Integer)
                    {
                        validMaxTimeLoggedIn = true;
                        maxTimeLoggedIn      = (UInt64)maxTimeLoggedInField;
                    }
                    if (validMaxTimeLoggedIn)
                    {
                        bool   validExcludeUntil = false;
                        string excludeUntil      = null;
                        if (!APIHelper.RequestBodyContainsField(requestBody, "excludeUntil", out JToken excludeUntilField) || (excludeUntilField.Type == JTokenType.Null))
                        {
                            validExcludeUntil = true;
                        }
                        else if (excludeUntilField.Type == JTokenType.Date)
                        {
                            validExcludeUntil = true;
                            excludeUntil      = APIHelper.APIDateTimeStringFromDateTime((DateTime)excludeUntilField);
                        }
                        else if (APIHelper.IsValidAPIDateTimeString((string)excludeUntilField))
                        {
                            validExcludeUntil = true;
                            excludeUntil      = (string)excludeUntilField;
                        }
                        if (validExcludeUntil)
                        {
                            if (Helper.AllFieldsRecognized(requestBody,
                                                           new List <string>(new String[] {
                                "maxDailySpendingAmount",
                                "maxTimeLoggedIn",
                                "excludeUntil"
                            })))
                            {
                                return(new SetUserLimitsRequest {
                                    maxDailySpendingAmount = maxDailySpendingAmount,
                                    maxTimeLoggedIn = maxTimeLoggedIn,
                                    excludeUntil = excludeUntil
                                });
                            }
                            else
                            {
                                // Unrecognised field(s)
                                Debug.Tested();
                                error = APIHelper.UNRECOGNISED_FIELD;
                            }
                        }
                        else
                        {
                            Debug.Untested();
                            error = IdentityServiceLogicLayer.INVALID_EXCLUDE_UNTIL;
                        }
                    }
                    else
                    {
                        Debug.Untested();
                        error = IdentityServiceLogicLayer.INVALID_MAX_TIME_LOGGED_IN;
                    }
                }
                else
                {
                    Debug.Untested();
                    error = IdentityServiceLogicLayer.INVALID_MAX_DAILY_SPENDING_AMOUNT;
                }
            }
            else
            {
                // No body
                Debug.Tested();
                error = APIHelper.NO_REQUEST_BODY;
            }
            throw APIHelper.CreateInvalidInputParameterException(error);
        }
        /**
         * Check validity of get ticket price audits request inputs.
         */
        internal static GetCountryAuditsRequest CheckValidGetCountryAuditsRequest(JObject requestBody)
        {
            Debug.Tested();
            Debug.AssertValidOrNull(requestBody);

            string error = null;

            if (requestBody != null)
            {
                Debug.Tested();
                bool   validFrom = false;
                string from      = null;
                if (APIHelper.RequestBodyContainsField(requestBody, "from", out JToken fromField))
                {
                    if (fromField.Type == JTokenType.Date)
                    {
                        validFrom = true;
                        from      = APIHelper.APIDateTimeStringFromDateTime((DateTime)fromField);
                    }
                    else if (APIHelper.IsValidAPIDateTimeString((string)fromField))
                    {
                        validFrom = true;
                        from      = (string)fromField;
                    }
                }
                if (validFrom)
                {
                    Debug.Tested();
                    bool   validTo = false;
                    string to      = null;
                    if (APIHelper.RequestBodyContainsField(requestBody, "to", out JToken toField))
                    {
                        if (toField.Type == JTokenType.Date)
                        {
                            validTo = true;
                            to      = APIHelper.APIDateTimeStringFromDateTime((DateTime)toField);
                        }
                        else if (APIHelper.IsValidAPIDateTimeString((string)toField))
                        {
                            validTo = true;
                            to      = (string)toField;
                        }
                    }
                    if (validTo)
                    {
                        Debug.Tested();
                        if (Helper.AllFieldsRecognized(requestBody,
                                                       new List <string>(new String[] {
                            "from",
                            "to"
                        })))
                        {
                            // Valid request
                            Debug.Tested();
                            return(new GetCountryAuditsRequest {
                                from = from,
                                to = to
                            });
                        }
                        else
                        {
                            // Unrecognised field(s)
                            Debug.Tested();
                            error = APIHelper.UNRECOGNISED_FIELD;
                        }
                    }
                    else
                    {
                        // Missing/invalid to
                        Debug.Tested();
                    }
                }
                else
                {
                    // Missing/invalid from
                    Debug.Tested();
                }
            }
            else
            {
                // No body
                Debug.Tested();
                error = APIHelper.NO_REQUEST_BODY;
            }
            throw APIHelper.CreateInvalidInputParameterException(error);
        }
        /**
         * Login
         */
        internal async Task <APIGatewayProxyResponse> Login(IDataStores dataStores, JObject requestBody)
        {
            Debug.Untested();
            Debug.AssertValidOrNull(requestBody);

            try {
                // Log call
                LoggingHelper.LogMessage($"UserIdentityService::Login()");

                // Get the NoSQL DB client
                AmazonDynamoDBClient dbClient = (AmazonDynamoDBClient)dataStores.GetNoSQLDataStore().GetDBClient();
                Debug.AssertValid(dbClient);

                // Check inputs
                LoginRequest loginRequest = UserIdentityService_Login_LogicLayer.CheckValidLoginRequest(requestBody);
                Debug.AssertValid(loginRequest);

                // Perform logic
                LoginResponse            response = new LoginResponse();
                Tuple <string, DateTime> result   = await UserIdentityService_Login_LogicLayer.Login(dbClient, loginRequest);

                Debug.AssertValid(result);
                response.accessToken = result.Item1;
                response.expiryTime  = APIHelper.APIDateTimeStringFromDateTime(result.Item2);

                // Respond
                return(new APIGatewayProxyResponse {
                    StatusCode = APIHelper.STATUS_CODE_OK,
                    Body = JsonConvert.SerializeObject(response)
                });
            } catch (Exception exception) {
                Debug.Tested();
                if ((exception.Message == SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS) ||
                    (exception.Message == IdentityServiceLogicLayer.ERROR_INCORRECT_PASSWORD) ||
                    (exception.Message == IdentityServiceLogicLayer.ERROR_USER_ACCOUNT_CLOSED) ||
                    (exception.Message == IdentityServiceLogicLayer.ERROR_USER_BLOCKED) ||
                    (exception.Message == IdentityServiceLogicLayer.ERROR_USER_LOCKED))
                {
                    Debug.Tested();
                    string error = null;
                    if (exception.Message == SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS)
                    {
                        Debug.Tested();
                        error = IdentityServiceLogicLayer.USER_NOT_FOUND;
                    }
                    else if (exception.Message == IdentityServiceLogicLayer.ERROR_INCORRECT_PASSWORD)
                    {
                        Debug.Tested();
                        error = IdentityServiceLogicLayer.USER_NOT_FOUND;
                    }
                    else if (exception.Message == IdentityServiceLogicLayer.ERROR_USER_ACCOUNT_CLOSED)
                    {
                        Debug.Tested();
                        error = IdentityServiceLogicLayer.ACCOUNT_CLOSED;
                    }
                    else if (exception.Message == IdentityServiceLogicLayer.ERROR_USER_BLOCKED)
                    {
                        Debug.Tested();
                        error = IdentityServiceLogicLayer.USER_BLOCKED;
                    }
                    else if (exception.Message == IdentityServiceLogicLayer.ERROR_USER_LOCKED)
                    {
                        Debug.Tested();
                        error = IdentityServiceLogicLayer.USER_LOCKED;
                    }
                    //??-- ObjectResult result = new ObjectResult(response);
                    // result.StatusCode = APIHelper.STATUS_CODE_UNAUTHORIZED;
                    // return result;
                    return(new APIGatewayProxyResponse {
                        StatusCode = APIHelper.STATUS_CODE_UNAUTHORIZED,
                        Body = $"{{ error = \"{error}\"}}"
                    });
                }
                else
                {
                    Debug.Tested();
                    return(APIHelper.ResponseFromException(exception));
                }
            }
        }
예제 #8
0
        /**
         * Add a user record to the data store.
         */
        internal static async Task AddUser(AmazonDynamoDBClient dbClient, User user)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(user);
            Debug.AssertID(user.ID);

            Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();

            item.Add(FIELD_USERS_ID, new AttributeValue(user.ID));
            item.Add(FIELD_USERS_CLIENT_ID, new AttributeValue(user.ClientID));
            item.Add(FIELD_USERS_GIVEN_NAME, new AttributeValue(user.GivenName));
            item.Add(FIELD_USERS_FAMILY_NAME, new AttributeValue(user.FamilyName));
            item.Add(FIELD_USERS_PREFERRED_NAME, new AttributeValue(user.PreferredName));
            item.Add(FIELD_USERS_FULL_NAME, new AttributeValue(user.FullName));
            item.Add(FIELD_USERS_EMAIL_ADDRESS, new AttributeValue(user.EmailAddress));
            item.Add(FIELD_USERS_EMAIL_ADDRESS_VERIFIED, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.EmailAddressVerified)));
            item.Add(FIELD_USERS_NEW_EMAIL_ADDRESS, new AttributeValue(user.NewEmailAddress));
            item.Add(FIELD_USERS_PASSWORD_HASH, new AttributeValue(user.PasswordHash));
            item.Add(FIELD_USERS_BLOCKED, new AttributeValue {
                BOOL = user.Blocked
            });
            item.Add(FIELD_USERS_LOCKED, new AttributeValue {
                BOOL = user.Locked
            });
            item.Add(FIELD_USERS_DATE_OF_BIRTH, new AttributeValue(APIHelper.APIDateStringFromDate(user.DateOfBirth)));
            item.Add(FIELD_USERS_GENDER, new AttributeValue {
                N = user.Gender.ToString()
            });
            item.Add(FIELD_USERS_ADDRESS_1, new AttributeValue(user.Address1));
            item.Add(FIELD_USERS_ADDRESS_2, new AttributeValue(user.Address2));
            item.Add(FIELD_USERS_ADDRESS_3, new AttributeValue(user.Address3));
            item.Add(FIELD_USERS_ADDRESS_4, new AttributeValue(user.Address4));
            item.Add(FIELD_USERS_CITY, new AttributeValue(user.City));
            item.Add(FIELD_USERS_REGION, new AttributeValue(user.Region));
            item.Add(FIELD_USERS_COUNTRY, new AttributeValue(user.Country));
            item.Add(FIELD_USERS_POSTAL_CODE, new AttributeValue(user.PostalCode));
            item.Add(FIELD_USERS_PHONE_NUMBER, new AttributeValue(user.PhoneNumber));
            item.Add(FIELD_USERS_PHONE_NUMBER_VERIFIED, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.PhoneNumberVerified)));
            item.Add(FIELD_USERS_LAST_LOGGED_IN, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.LastLoggedIn)));
            item.Add(FIELD_USERS_LAST_LOGGED_OUT, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.LastLoggedOut)));
            item.Add(FIELD_USERS_CLOSED, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.Closed)));
            item.Add(FIELD_USERS_IS_ANONYMISED, new AttributeValue {
                BOOL = user.IsAnonymised
            });
            item.Add(FIELD_USERS_DELETED, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.Deleted)));
            item.Add(FIELD_USERS_ALLOW_NON_ESSENTIAL_EMAILS, new AttributeValue {
                BOOL = user.AllowNonEssentialEmails
            });
            item.Add(FIELD_USERS_ANEE_ON_TIMESTAMP, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.ANEEOnTimestamp)));
            item.Add(FIELD_USERS_ANEE_OFF_TIMESTAMP, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.ANEEOffTimestamp)));
            item.Add(FIELD_USERS_TOTAL_TICKETS_PURCHASED, new AttributeValue {
                N = user.TotalTicketsPurchased.ToString()
            });
            item.Add(FIELD_USERS_TICKETS_PURCHASED_IN_CURRENT_GAME, new AttributeValue {
                N = user.TicketsPurchasedInCurrentGame.ToString()
            });
            item.Add(FIELD_USERS_PREFERRED_LANGUAGE, new AttributeValue(user.PreferredLanguage));
            item.Add(FIELD_USERS_PREFERRED_CURRENCY, new AttributeValue(user.PreferredCurrency));
            item.Add(FIELD_USERS_PREFERRED_TIME_ZONE, new AttributeValue(user.PreferredTimeZone));
            item.Add(FIELD_USERS_FAILED_LOGIN_ATTEMPTS, new AttributeValue {
                N = user.FailedLoginAttempts.ToString()
            });
            item.Add(FIELD_USERS_KYC_STATUS, new AttributeValue(user.KYCStatus));
            item.Add(FIELD_USERS_KYC_TIMESTAMP, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.KCYTimestamp)));
            item.Add(FIELD_USERS_MAX_DAILY_SPENDING_AMOUNT, new AttributeValue {
                N = user.MaxDailySpendingAmount.ToString()
            });
            item.Add(FIELD_USERS_NEW_MAX_DAILY_SPENDING_AMOUNT, new AttributeValue {
                N = user.NewMaxDailySpendingAmount.ToString()
            });
            item.Add(FIELD_USERS_NEW_MAX_DAILY_SPENDING_AMOUNT_TIME, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.NewMaxDailySpendingAmountTime)));
            item.Add(FIELD_USERS_MAX_TIME_LOGGED_IN, new AttributeValue {
                N = user.MaxTimeLoggedIn.ToString()
            });
            item.Add(FIELD_USERS_NEW_MAX_TIME_LOGGED_IN, new AttributeValue {
                N = user.NewMaxTimeLoggedIn.ToString()
            });
            item.Add(FIELD_USERS_NEW_MAX_TIME_LOGGED_IN_TIME, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.NewMaxTimeLoggedInTime)));
            item.Add(FIELD_USERS_EXCLUDE_UNTIL, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.ExcludeUntil)));
            item.Add(FIELD_USERS_NEW_EXCLUDE_UNTIL, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntil)));
            item.Add(FIELD_USERS_NEW_EXCLUDE_UNTIL_TIME, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntilTime)));
            item.Add(FIELD_USERS_PERMISSIONS, new AttributeValue {
                SS = user.Permissions
            });
            PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_USERS, item);

            Debug.AssertValid(putResponse);
            //??++Check response?
        }