Example #1
0
        public async Task <PlatformDataUserTestResult> TestUserDataFromPlatformAsync(UserDataRequest request, string exportDataUri)
        {
            var response = await GetUserDataFromPlatformResponseAsync(request, exportDataUri);

            var stringResult = await response.Content.ReadAsStringAsync();

            PlatformDataUserUpdateResult result = null;

            if (response.IsSuccessStatusCode)
            {
                try
                {
                    result = JsonConvert.DeserializeObject <PlatformDataUserUpdateResult>(stringResult);
                }
                catch (Exception)
                {
                    _logger.LogInformation("Could not deserialize response from platform.");
                }
            }

            return(new PlatformDataUserTestResult(result,
                                                  new TestRequest(null, request
                                                                  )
                                                  , new TestResponse(
                                                      response.Headers.Select(item => string.Format("{0} : {1}", item.Key, string.Join(", ", item.Value))).ToArray()
                                                      , response.StatusCode.ToString()
                                                      , stringResult
                                                      )));
        }
Example #2
0
        public async Task <StorageResponse <bool> > DropLoginAsync(UserDataRequest userData)
        {
            if (userData.Username.IsNullOrEmpty())
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = new ArgumentNullException(nameof(userData.Username))
                });
            }

            var killResult = await KillUserConncetionsAsync(userData.Server, userData.Username);

            if (killResult.IsFaulty)
            {
                return(killResult);
            }

            try
            {
                await ExecuteNonQueryAsync(userData.Server, $"{ConstantsMsSql.DROP} {ConstantsMsSql.LOGIN} [{userData.Username}]", ConstantsMsSql.MASTER);
            }
            catch (Exception ex)
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = ex
                });
            }

            return(new StorageResponse <bool> {
                Data = true
            });
        }
Example #3
0
        public async Task <List <UserDataDto> > GetUsersDataAsync(string accessToken)
        {
            var userDataClient = new HttpClient();

            userDataClient.DefaultRequestHeaders.Add("Accept", "application/json");
            userDataClient.DefaultRequestHeaders.Add("Authorization", "bearer " + accessToken);

            var userDataRequest = new UserDataRequest
            {
                sql = "SELECT * FROM table",
            };

            var userDatarequestJson = JsonConvert.SerializeObject(userDataRequest);

            //TODO: move URL to app config
            var url = "https://api.domo.com/v1/datasets/query/execute/8b209fa4-bb92-4b39-8e73-3f4183542129";

            var userDataResponse = userDataClient.PostAsync(url, new StringContent(userDatarequestJson, Encoding.UTF8, "application/json")).Result;

            userDataResponse.EnsureSuccessStatusCode();
            var dataSetJsonString = await userDataResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            var usersData = ConvertUsersJsonToDto(dataSetJsonString);

            return(usersData);
        }
Example #4
0
 public void GetUserData(UserDataRequest request, Action <CloudData> callback)
 {
     Instance.StartCoroutine(ServiceGetString(callObjectCreator.CreateUserDataCall(request), x =>
     {
         if (callback != null)
         {
             callback(responseCreator.CreateCloudDataResponse(x));
         }
     }));
 }
 /// <summary>
 /// Al recibir una solicitud de datos de un usuario
 /// </summary>
 /// <param name="sender">Emisor</param>
 /// <param name="e">Solicitud</param>
 private void User_OnDataRequest(object sender, UserDataRequest e)
 {
     if (sender is User user)
     {
         if (e.DataRequest == DATA_REQUEST_DEVICES)
         {
             user.Write(m_devicesDataService.GetSerializableDevices());
         }
         if (e.DataRequest == PING)
         {
             var credential = ConfigurationManager.Get <IServerCredential>();
             var response   = new PingResponse(credential != null ? credential.ServerId : "");
             user.Write(response);
         }
     }
 }
Example #6
0
        public async Task <StorageResponse <bool> > CreateLoginAsync(UserDataRequest userData)
        {
            if (userData.Username.IsNullOrEmpty())
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = new ArgumentNullException(nameof(userData.Username))
                });
            }

            if (userData.Password.IsNullOrEmpty())
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = new ArgumentNullException(nameof(userData.Password))
                });
            }

            if (userData.Password.Contains(ConstantsMsSql.COMMENT) || userData.Password.Contains(ConstantsMsSql.STRING))
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = new NotSupportedException("At least one signs is not supported")
                });
            }

            var sqlCommand = new StringBuilder();

            sqlCommand.Append($"{ConstantsMsSql.CREATE} {ConstantsMsSql.LOGIN} [{userData.Username}] ");
            sqlCommand.Append($"{ConstantsMsSql.WITH} {ConstantsMsSql.PASSWORD} = '{userData.Password}', ");
            sqlCommand.Append($"{ConstantsMsSql.CHECK_POLICY}={ConstantsMsSql.OFF}, ");
            sqlCommand.AppendLine($"{ConstantsMsSql.DEFAULT_DATABASE}=[{userData.Server.DatabaseName}];");

            try
            {
                await ExecuteNonQueryAsync(userData.Server, sqlCommand.ToString(), ConstantsMsSql.MASTER);
            }
            catch (Exception ex)
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = ex
                });
            }

            return(new StorageResponse <bool> {
                Data = true
            });
        }
        public void GetNewUserdata()
        {
            if (_client == null)
            {
                return;
            }
            var userId = new UserIdentification {
                Usertoken = UserData.Usertoken, Secret = "????"
            };
            var req = new UserDataRequest {
                UserIdent = userId, Username = UserData.Username
            };
            var ud = _client.Call.GetPublicUserdata(req);

            //WAAAAA. Make sure not to overwrite the usertoken
            UserData = new UserData {
                Username = UserData.Username, Usertoken = UserData.Usertoken, Elo = ud.Elo
            };
        }
        public static GymDataResponse gymLoginImplementation(UserDataRequest request)
        {
            using (var db = new UniversalGymEntities())
            {
                if (String.IsNullOrWhiteSpace(request.emailAddress))
                {
                    return(new GymDataResponse
                    {
                        message = "Please enter an email.",
                        status = 404,
                        success = false,
                    });
                }

                if (String.IsNullOrWhiteSpace(request.password))
                {
                    return(new GymDataResponse
                    {
                        message = "Please enter a password.",
                        status = 404,
                        success = false,
                    });
                }


                // admin access
                if (!request.password.Equals(Constants.MarketingToken))
                {
                    if (!MembershipHelper.userExists(request.emailAddress, request.password, Constants.GymRole))
                    {
                        return(new GymDataResponse {
                            message = "Username or Password incorrect!!", status = 401, success = false
                        });;
                    }
                }

                var  user = MembershipHelper.getUser(request.emailAddress, Constants.GymRole);
                Guid guid = Guid.Parse(user.ProviderUserKey.ToString());
                var  gym  = db.Gyms.FirstOrDefault(cs => cs.GymGuid == guid);

                return(gymDataHelper.CreateGymDataResponse(gym.GymId, true));
            }
        }
        public async Task <IActionResult> GetUserData(UserDataRequest userDataRequest)
        {
            Serilog.Log.Information("Request {userDataRequest}", userDataRequest);

            // Check the PlatformToken for validity
            if (userDataRequest?.PlatformToken == null || userDataRequest.PlatformToken != _gigDataServiceConfig.PlatformToken)
            {
                Serilog.Log.Error("Incorrect PlatformToken. Token {PlatformToken}", _gigDataServiceConfig?.PlatformToken);

                // There are multiple registrations for the main mock platform
                // service now, so disabling this requirement
                //throw new Exception("MyGigDataToken mismatch.");
            }

            using (IAsyncDocumentSession session = _documentStore.OpenAsyncSession())
            {
                var user = await session
                           .Query <User>()
                           .Where(u => u.UserEmail == userDataRequest.UserEmail)
                           .FirstOrDefaultAsync();

                if (user == null)
                {
                    return(NotFound(new
                    {
                        message = $"Unable to find that user. Request UserEmail: '{userDataRequest.UserEmail}'"
                    }));
                }
                Serilog.Log.Information("User", user);

                UserDataResponse response = new UserDataResponse {
                    Id           = user.Id,
                    RequestId    = userDataRequest.RequestId,
                    UserEmail    = user.UserEmail,
                    Interactions = user.Interactions,
                    Achievements = user.Achievements
                };

                return(Ok(response));
            }
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static AllDataResponse userLoginImplementation(UserDataRequest request)
        {
            using (var db = new UniversalGymEntities())
            {
                if (String.IsNullOrWhiteSpace(request.emailAddress))
                {
                    return(new AllDataResponse
                    {
                        message = "Please enter an email.",
                        status = 404,
                        success = false,
                    });
                }

                if (String.IsNullOrWhiteSpace(request.password))
                {
                    return(new AllDataResponse
                    {
                        message = "Please enter a password.",
                        status = 404,
                        success = false,
                    });
                }

                if (!MembershipHelper.userExists(request.emailAddress, request.password, Constants.UserRole))
                {
                    return(new AllDataResponse {
                        message = "Username or Password incorrect", status = 5, success = false
                    });
                }

                MembershipUser user     = MembershipHelper.getUser(request.emailAddress, Constants.UserRole);
                Guid           userGuid = Guid.Parse(user.ProviderUserKey.ToString());

                var user2 = (from cs in db.Users
                             where cs.UserGuid == userGuid
                             select cs).FirstOrDefault();

                return(allDataHelper.CreateAllDataResponse(user2.UserId, true));
            }
        }
Example #11
0
        public async Task <StorageResponse <bool> > AddUserToDatabaseAsync(UserDataRequest userData)
        {
            if (userData.Username.IsNullOrEmpty())
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = new ArgumentNullException(nameof(userData.Username))
                });
            }

            if (userData.Server.DatabaseName.IsNullOrEmpty())
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = new ArgumentNullException(nameof(userData.Server.DatabaseName))
                });
            }

            var sqlCommand = new StringBuilder();

            sqlCommand.AppendLine($"{ConstantsMsSql.CREATE} {ConstantsMsSql.USER} [{userData.Username}];");
            sqlCommand.AppendLine($"{ConstantsMsSql.EXEC} {ConstantsMsSql.SP_ADDROLEMEMBER} N'{ConstantsMsSql.DBROLE_READER}', N'{userData.Username}';");
            sqlCommand.AppendLine($"{ConstantsMsSql.EXEC} {ConstantsMsSql.SP_ADDROLEMEMBER} N'{ConstantsMsSql.DBROLE_WRITER}', N'{userData.Username}';");
            sqlCommand.AppendLine($"{ConstantsMsSql.EXEC} {ConstantsMsSql.SP_ADDROLEMEMBER} N'{ConstantsMsSql.DBROLE_BACKUP}', N'{userData.Username}';");
            sqlCommand.AppendLine($"{ConstantsMsSql.EXEC} {ConstantsMsSql.SP_ADDROLEMEMBER} N'{ConstantsMsSql.DBROLE_DDLADMIN}', N'{userData.Username}';");
            sqlCommand.AppendLine($"{ConstantsMsSql.GRANT_EXECUTE_TO} [{userData.Username}];");

            try
            {
                await ExecuteNonQueryAsync(userData.Server, sqlCommand.ToString());
            }
            catch (Exception ex)
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = ex
                });
            }

            return(new StorageResponse <bool> {
                Data = true
            });
        }
        // FUNCTIONS FOR GYMS


        // LOGGING IN

        // gym login
        public GymDataResponse GymLogin(UserDataRequest request)
        {
            try
            {
                Logs.LogsInsertAction("Gym login attempted");
                var validResponse = Gym.gymLogin.gymLoginImplementation(request);
                if (validResponse.success == true)
                {
                    Logs.LogsInsertAction("Gym login success: " + validResponse.message);
                }
                else
                {
                    Logs.LogsInsertAction("Gym login failure: " + validResponse.message);
                }
                return(validResponse);
            }
            catch (Exception exception)
            {
                Logs.LogsInsertError(exception);
                return(new GymDataResponse {
                    message = "An error occured. The Pedal team has been notified.", success = false
                });
            }
        }
        public async Task <IActionResult> TestApi([FromRoute] string id, [FromBody] UserDataTestApiModel request)
        {
            _logger.LogInformation("Testing platform {id}: {@request}", id, request);


            using var session = _documentStore.OpenAsyncSession();
            // Get platform
            var platform = await _platformManager.GetPlatformAsync(id, session);

            // If there is no connection, check that the platform exists
            if (platform == null)
            {
                // TODO: Log this
                return(NotFound(PlatformUserDataResponse.Fail("", $"No platform found with ID '{id}'. [-]")));
            }

            if (string.IsNullOrEmpty(platform.ExportDataUri))
            {
                throw new ApiException(message: "The platform setup is incomplete.", errors: new List <string> {
                    "Missing ExportDataUri."
                });
            }

            UserDataRequest userDataRequest = new UserDataRequest(platform.PlatformToken, request.UserEmail, Guid.NewGuid().ToString());

            var response = await _platformHttpClient.TestUserDataFromPlatformAsync(userDataRequest, platform.ExportDataUri);

            if (response.Response.Status == "NotFound")
            {
                throw new ApiException(message: "The server responded with NotFound.", errors: new List <string> {
                    "Response: " + response.Response.Body
                });
            }

            return(Ok(response));
        }
Example #14
0
        public async Task <StorageResponse <bool> > DropUserFromDatabaseAsync(UserDataRequest userData)
        {
            if (userData.Username.IsNullOrEmpty())
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = new ArgumentNullException(nameof(userData.Username))
                });
            }

            try
            {
                await ExecuteNonQueryAsync(userData.Server, $"{ConstantsMsSql.DROP} {ConstantsMsSql.USER} [{userData.Username}]");
            }
            catch (Exception ex)
            {
                return(new StorageResponse <bool> {
                    IsFaulty = true, Exception = ex
                });
            }

            return(new StorageResponse <bool> {
                Data = true
            });
        }
Example #15
0
        private async Task <HttpResponseMessage> GetUserDataFromPlatformResponseAsync(UserDataRequest request, string exportDataUri)
        {
            _client.BaseAddress = new Uri(exportDataUri);

            // For GETting the user data from the external platform
            //_client.DefaultRequestHeaders.Add("platformToken", request.PlatformToken);
            //_client.DefaultRequestHeaders.Add("username", request.Username);
            //_client.DefaultRequestHeaders.Add("requestId", request.RequestId);
            //var response = await _client.GetAsync("");

            var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
            HttpResponseMessage response;

            try
            {
                response = await _client.PostAsync(exportDataUri, content);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Could not communicate with the platform. Will throw.");
                throw new PlatformCommunicationException("Could not communicate with platform.");
            }

            return(response);
        }
Example #16
0
 public WWW CreateUserDataCall(UserDataRequest request)
 {
     return(GenerateWWWPost("UserData", request));
 }
Example #17
0
        public async Task <PlatformDataUserUpdateResult> GetUserDataFromPlatformAsync(UserDataRequest request, string exportDataUri)
        {
            var response = await GetUserDataFromPlatformResponseAsync(request, exportDataUri);

            if (!response.IsSuccessStatusCode)
            {
                switch (response.StatusCode)
                {
                case HttpStatusCode.NotFound:
                    throw new UserNotFoundForPlatformException(request.UserEmail, "Platform reported non existant user");

                default:
                    throw new PlatformCommunicationException($"Got unhandled http status code {response.StatusCode} from platform");
                }
            }

            var stringResult = await response.Content.ReadAsStringAsync();

            PlatformDataUserUpdateResult result;

            try
            {
                result         = JsonConvert.DeserializeObject <PlatformDataUserUpdateResult>(stringResult);
                result.RawData = stringResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Could not parse data provided by the platform.");
                throw new MalformedPlatformDataException(stringResult, "Could not parse data");
            }

            return(result);
        }
        public async Task <IActionResult> RequestLatest([FromBody] UserUpdateRequest request)
        {
            // Create an identifier this particular request
            var requestId = Guid.NewGuid().ToString();

            // Log the request
            _logger.LogInformation("Request for latest update {request}", request);
            using var session = _documentStore.OpenAsyncSession();
            // Get platform
            var platform = await _platformManager.GetPlatformAsync(request.PlatformId, session);

            // If there is no connection, check that the platform exists
            if (platform == null)
            {
                _logger.LogWarning("Platform not found {id}", request.PlatformId);
                return(NotFound(PlatformUserDataResponse.Fail(requestId, $"There is no platform registered with ID '{request.PlatformId}'.")));
            }

            if (string.IsNullOrEmpty(platform.ExportDataUri))
            {
                throw new ApiException(message: "The platform setup is incomplete.", errors: new List <string> {
                    "Missing ExportDataUri."
                });
            }

            UserDataRequest userDataRequest       = new UserDataRequest(platform.PlatformToken, request.Username, requestId);
            PlatformUserUpdateDataMessage message = null;

            try
            {
                var response = await _platformHttpClient.GetUserDataFromPlatformAsync(userDataRequest, platform.ExportDataUri);

                message = new PlatformUserUpdateDataMessage(requestId, request.Username, Guid.Parse(request.PlatformId), response);
            }
            catch (UserNotFoundForPlatformException ex)
            {
                _logger.LogInformation("Platform with id {platformId} reported that it could not find user with username {username}.",
                                       platform.Id, ex.UserEmail);
                message = new PlatformUserUpdateDataMessage(requestId, request.Username, Guid.Parse(request.PlatformId), null, PlatformDataUpdateResultType.UserNotFound);
            }
            catch (MalformedPlatformDataException ex)
            {
                _logger.LogInformation(ex, "Data from platform could not be understood");
                message = new PlatformUserUpdateDataMessage(requestId, request.Username, Guid.Parse(request.PlatformId), null, PlatformDataUpdateResultType.MalformedDataResponse);
            }
            catch (PlatformCommunicationException ex)
            {
                _logger.LogError(ex, "Could not communicate with the platform.");
                message = new PlatformUserUpdateDataMessage(requestId, request.Username, Guid.Parse(request.PlatformId), null, PlatformDataUpdateResultType.PlatformCommunicationError);
            }

            try
            {
                await _platformDispatchManager.SendUserDataMessage(message);

                return(Ok(PlatformUserDataResponse.Ok(requestId, $"Request for update received and dispatched to service bus.")));
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Unhandled exception in messaging");
                throw new ApiException(message: ex.Message, errors: new List <string> {
                    ex.StackTrace
                });
            }
        }
        public async Task <IActionResult> GetUserData()
        {
            UserDataRequest userDataRequest = new UserDataRequest(Request.Headers["platformToken"], Request.Headers["userEmail"], Request.Headers["requestId"]);

            return(await GetUserData(userDataRequest));
        }
 public static void UserDataGet(UserDataRequest request, Action <CloudData> callback)
 {
     CallHandler.Instance.GetUserData(request, callback);
 }