Beispiel #1
0
        private static void PerformanceTest()
        {
            ApiServer server = ApiServer.CreateDummy();

            using DatabaseManager databaseManager = new DatabaseManager(server);
            const string  query   = "SELECT id FROM Tbl_user WHERE id = 1 LIMIT 1";
            SqlApiRequest request = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
            const int     maxIter = 10000;

            Console.WriteLine("Performance Test: Sending " + maxIter.ToString() + " requests to DB server ...");
            Stopwatch stopwatch = Stopwatch.StartNew();

            for (int i = 0; i < maxIter; i++)
            {
                SqlSingleOrDefaultResponse response = databaseManager.AwaitSingleOrDefaultResponse(request, out bool success);
                if (!success)
                {
                    break;
                }
                Console.WriteLine("Request #" + i.ToString() + " succeeded!");
            }
            stopwatch.Stop();
            double average = stopwatch.ElapsedMilliseconds / (double)maxIter;

            Console.WriteLine("Average time per request: " + average.ToString() + " ms.");
        }
Beispiel #2
0
        public override void Process(ApiServer server)
        {
            if (server.AssertServerSetup(this) || server.AssertAuthenticationCodeInvalid(Code) || server.AssertUserOnline() || server.AssertPasswordSet() || server.AssertIdSet())
            {
                return;
            }
            using DatabaseManager databaseManager = new DatabaseManager(server);
            // Check if security token is valid.
            string        query      = DatabaseEssentials.Security.SanitizeQuery(new string[] { "SELECT u.id FROM Tbl_cookies as c, Tbl_user as u WHERE c.value = \'", SecurityToken, "\' AND u.id = c.userid;" });
            SqlApiRequest sqlRequest = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 2);
            SqlSingleOrDefaultResponse singleOrDefaultResponse = databaseManager.AwaitSingleOrDefaultResponse(sqlRequest, out bool success);

            if (!success)
            {
                return;
            }
            if (!singleOrDefaultResponse.Success || !singleOrDefaultResponse.Result.Equals(server.Account.Id))
            {
                ApiError.Throw(ApiErrorCode.InvalidToken, server, "Security token was invalid.");
                return;
            }
            // Reset security token expiration timer..
            int expirationDate = DatabaseEssentials.GetTimeStamp() + MainServer.Config.WamsrvSecurityConfig.SecurityTokenExpirationTime;

            query      = DatabaseEssentials.Security.SanitizeQuery(new string[] { "UPDATE Tbl_cookies SET expires = \'", expirationDate.ToString(), "\' WHERE value = \'", SecurityToken, "\';" });
            sqlRequest = SqlApiRequest.Create(SqlRequestId.ModifyData, query, -1);
            SqlModifyDataResponse modifyDataResponse = databaseManager.AwaitModifyDataResponse(sqlRequest, out success);

            if (!success)
            {
                return;
            }
            if (!modifyDataResponse.Success)
            {
                ApiError.Throw(ApiErrorCode.InternalServerError, server, "Unable to refresh security token.");
                return;
            }
            // Delete all other security tokens associated with the account.
            if (databaseManager.DeleteSecurityTokens(new string[] { SecurityToken }))
            {
                return;
            }
            // Update password.
            if (databaseManager.UpdatePassword())
            {
                return;
            }
            server.Account.AuthenticationCode = string.Empty;
            server.Account.AuthenticationId   = ApiRequestId.Invalid;
            server.Account.AuthenticationTime = -1;
            GenericSuccessResponse response = new GenericSuccessResponse(ResponseId.ConfirmAccount, true);
            SerializedApiResponse  serializedApiResponse = SerializedApiResponse.Create(response);
            string json = serializedApiResponse.Serialize();

            server.Send(json);
            server.UnitTesting.MethodSuccess = true;
        }
Beispiel #3
0
        public bool CheckEmailAvailable(string email, out bool success)
        {
            string        sanitizedEmail = DatabaseEssentials.Security.Sanitize(email);
            string        query          = "SELECT 1 FROM Tbl_user WHERE email = \'" + sanitizedEmail + "\' LIMIT 1;";
            SqlApiRequest sqlRequest     = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
            SqlSingleOrDefaultResponse singleOrDefaultResponse = this.AwaitSingleOrDefaultResponse(sqlRequest, out bool sqlSuccess);

            success = sqlSuccess;
            return(success && !singleOrDefaultResponse.Success);
        }
Beispiel #4
0
        public bool CheckUserExists(string userId, out bool success)
        {
            string        query      = "SELECT 1 FROM Tbl_user WHERE hid = \'" + DatabaseEssentials.Security.Sanitize(userId) + "\' LIMIT 1;";
            SqlApiRequest sqlRequest = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
            SqlSingleOrDefaultResponse singleOrDefaultResponse = AwaitSingleOrDefaultResponse(sqlRequest, out bool sqlSuccess);

            if (!sqlSuccess)
            {
                success = false;
                return(false);
            }
            success = true;
            return(singleOrDefaultResponse.Success);
        }
Beispiel #5
0
        public Permission GetUserPermission(string userId, out bool success)
        {
            string id = UserIdToId(userId, out bool sqlSuccess);

            if (!sqlSuccess)
            {
                success = false;
                return(Permission.NONE);
            }
            string        query      = "SELECT permissions FROM Tbl_admin WHERE userid = " + id + " LIMIT 1;";
            SqlApiRequest sqlRequest = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
            SqlSingleOrDefaultResponse singleOrDefaultResponse = AwaitSingleOrDefaultResponse(sqlRequest, out sqlSuccess);

            if (!sqlSuccess)
            {
                success = false;
                return(Permission.NONE);
            }
            if (!singleOrDefaultResponse.Success)
            {
                success = true;
                return(Permission.NONE);
            }
            bool parseSuccess = int.TryParse(singleOrDefaultResponse.Result, out int intPermission);

            if (!parseSuccess)
            {
                ApiError.Throw(ApiErrorCode.InternalServerError, server, "Unable to parse user permission.");
                success = false;
                return(Permission.NONE);
            }
            Permission permission = (Permission)intPermission;

            if (permission == Permission.NONE)
            {
                query      = "DELETE FROM Tbl_admin WHERE userid = " + id + ";";
                sqlRequest = SqlApiRequest.Create(SqlRequestId.ModifyData, query, -1);
                AwaitModifyDataResponse(sqlRequest, out sqlSuccess);
                if (!sqlSuccess)
                {
                    success = false;
                    return(Permission.NONE);
                }
            }
            success = true;
            return(permission);
        }
Beispiel #6
0
        public override async void Process(SqlServer server)
        {
            SqlPacket packet = await DatabaseManager.GetSingleOrDefault(Query);

            ApiResponse response;

            if (packet.Success)
            {
                string result = (string)packet.Data;
                response = SqlSingleOrDefaultResponse.Create(result);
            }
            else
            {
                response = SqlErrorResponse.Create(packet.ErrorMessage);
            }
            SerializedSqlApiResponse serializedApiResponse = SerializedSqlApiResponse.Create(response);
            string data = serializedApiResponse.Serialize();

            server.Network.Send(data);
        }
Beispiel #7
0
        public bool UserIsRoot(string userId, out bool success)
        {
            string        query      = "SELECT email FROM Tbl_user WHERE hid = \'" + DatabaseEssentials.Security.Sanitize(userId) + "\' LIMIT 1;";
            SqlApiRequest sqlRequest = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
            SqlSingleOrDefaultResponse singleOrDefaultResponse = AwaitSingleOrDefaultResponse(sqlRequest, out bool sqlSuccess);

            if (!sqlSuccess)
            {
                success = false;
                return(false);
            }
            if (!singleOrDefaultResponse.Success)
            {
                ApiError.Throw(ApiErrorCode.InvalidUser, server, "User could not be found.");
                success = false;
                return(false);
            }
            success = true;
            return(singleOrDefaultResponse.Result.Equals(MainServer.Config.WamsrvEmailConfig.EmailAddress));
        }
Beispiel #8
0
        /// <summary>
        /// Throws an exception if the EventID is invalid and returns true otherwise.
        /// </summary>
        /// <param name="server"></param>
        /// <param name="eventId"></param>
        /// <returns></returns>
        public bool AssertEventExists(string eventId)
        {
            if (string.IsNullOrEmpty(eventId))
            {
                ApiError.Throw(ApiErrorCode.InvalidArgument, server, "Invalid argument: EventID was null.");
                return(true);
            }
            string        query      = DatabaseEssentials.Security.SanitizeQuery(new string[] { "SELECT 1 FROM Tbl_event WHERE hid = \'", eventId, "\' LIMIT 1;" });
            SqlApiRequest sqlRequest = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
            SqlSingleOrDefaultResponse singleOrDefaultResponse = AwaitSingleOrDefaultResponse(sqlRequest, out bool success);

            if (!success)
            {
                return(true);
            }
            if (!singleOrDefaultResponse.Success)
            {
                ApiError.Throw(ApiErrorCode.NotFound, server, "There is no event associated with this EventID.");
                return(true);
            }
            return(false);
        }
Beispiel #9
0
        public string UserIdToId(string userid, out bool success)
        {
            string        sanitizedUserId = DatabaseEssentials.Security.Sanitize(userid);
            string        query           = "SELECT id FROM Tbl_user WHERE hid = \'" + sanitizedUserId + "\' LIMIT 1;";
            SqlApiRequest sqlRequest      = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
            SqlSingleOrDefaultResponse singleOrDefaultResponse = this.AwaitSingleOrDefaultResponse(sqlRequest, out bool sqlSuccess);

            if (!sqlSuccess)
            {
                success = false;
                return(string.Empty);
            }
            string id = singleOrDefaultResponse.Result;

            if (!singleOrDefaultResponse.Success)
            {
                ApiError.Throw(ApiErrorCode.InvalidUser, server, "User could not be found.");
                success = false;
                return(string.Empty);
            }
            success = true;
            return(id);
        }
Beispiel #10
0
 public bool OptionalAssertUserExists(string id, bool isDatabaseId)
 {
     if (MainServer.Config.AdvancedErrorChecking)
     {
         string query;
         if (isDatabaseId)
         {
             query = "SELECT 1 FROM Tbl_user WHERE id = " + DatabaseEssentials.Security.Sanitize(id) + ";";
         }
         else
         {
             query = "SELECT 1 FROM Tbl_user WHERE hid = \'" + DatabaseEssentials.Security.Sanitize(id) + "\';";
         }
         SqlApiRequest sqlRequest = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
         SqlSingleOrDefaultResponse singleOrDefaultResponse = AwaitSingleOrDefaultResponse(sqlRequest, out bool success);
         if (!success)
         {
             return(true);
         }
         return(!singleOrDefaultResponse.Success);
     }
     return(false);
 }
Beispiel #11
0
        public override void Process(ApiServer server)
        {
            if (server.AssertServerSetup(this) || server.AssertUserOnline())
            {
                return;
            }
            using DatabaseManager databaseManager = new DatabaseManager(server);
            if (databaseManager.AssertEventExists(EventId) || databaseManager.AssertHasPermission(Permission.QUERY_EVENT_INFO))
            {
                return;
            }
            EventInfo eventInfo = databaseManager.GetEventInfo(EventId, out bool success);

            if (!success)
            {
                return;
            }
            string        query      = "SELECT u.hid FROM Tbl_event as e, Tbl_user as u WHERE e.hid = \'" + DatabaseEssentials.Security.Sanitize(EventId) + "\' AND e.userid = u.id LIMIT 1;";
            SqlApiRequest sqlRequest = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
            SqlSingleOrDefaultResponse singleOrDefaultResponse = databaseManager.AwaitSingleOrDefaultResponse(sqlRequest, out success);

            if (!success)
            {
                return;
            }
            if (!singleOrDefaultResponse.Success)
            {
                ApiError.Throw(ApiErrorCode.InternalServerError, server, "Unable to fetch event.");
                return;
            }
            GetEventResponseA     response = new GetEventResponseA(ResponseId.GetEventA, new Event(eventInfo, singleOrDefaultResponse.Result));
            SerializedApiResponse serializedApiResponse = SerializedApiResponse.Create(response);
            string json = serializedApiResponse.Serialize();

            server.Send(json);
            server.UnitTesting.MethodSuccess = true;
        }
Beispiel #12
0
        public override void Process(ApiServer server)
        {
            if (server.AssertServerSetup(this) || AccountInfo == null)
            {
                ApiError.Throw(ApiErrorCode.InvalidArgument, server, "AccountInfo was null.");
                return;
            }
            if (server.AssertUserOnline() || server.AssertIdSet() || server.AssertAccountInfoNotNull())
            {
                return;
            }
            using DatabaseManager databaseManager = new DatabaseManager(server);
            string query;
            bool   success;

            if (string.IsNullOrEmpty(server.Account.AccountInfo.UserId))
            {
                query = "SELECT hid FROM Tbl_user WHERE id = " + DatabaseEssentials.Security.Sanitize(server.Account.Id);
                SqlApiRequest sqlRequest = SqlApiRequest.Create(SqlRequestId.GetSingleOrDefault, query, 1);
                SqlSingleOrDefaultResponse singleOrDefaultResponse = databaseManager.AwaitSingleOrDefaultResponse(sqlRequest, out success);
                if (!success)
                {
                    return;
                }
                if (!singleOrDefaultResponse.Success)
                {
                    ApiError.Throw(ApiErrorCode.InternalServerError, server, "Unable to determine userid.");
                    return;
                }
                server.Account.AccountInfo.UserId = singleOrDefaultResponse.Result;
            }
            AesContext    aesContext       = new AesContext(server.Account.AccountInfo.UserId);
            string        cryptoName       = aesContext.EncryptOrDefault(AccountInfo.Name);
            string        cryptoOccupation = aesContext.EncryptOrDefault(AccountInfo.Occupation);
            StringBuilder stringBuilder    = new StringBuilder();

            string[] infos = new string[] { AccountInfo.Info1, AccountInfo.Info2, AccountInfo.Info3, AccountInfo.Info4, AccountInfo.Info5, AccountInfo.Info6, AccountInfo.Info7, AccountInfo.Info8, AccountInfo.Info9, AccountInfo.Info10 };
            for (int i = 0; i < infos.Length; i++)
            {
                stringBuilder.Append(", info").Append((i + 1).ToString()).Append(" = \'").Append(aesContext.EncryptOrDefault(infos[i])).Append('\'');
            }
            query = "UPDATE Tbl_user SET name = \'" + cryptoName + "\', occupation = \'" + cryptoOccupation + "\'" + stringBuilder.ToString() + ", location = \'" + DatabaseEssentials.Security.Sanitize(AccountInfo.Location) + "\', radius = " + AccountInfo.Radius.ToString() + ", isVisible = " + (AccountInfo.IsVisible ? "1" : "0") + ", showLog = " + (AccountInfo.ShowLog ? "1" : "0") + " WHERE id = " + DatabaseEssentials.Security.Sanitize(server.Account.Id) + ";";
            SqlApiRequest         sqlApiRequest      = SqlApiRequest.Create(SqlRequestId.ModifyData, query, -1);
            SqlModifyDataResponse modifyDataResponse = databaseManager.AwaitModifyDataResponse(sqlApiRequest, out success);

            if (!success)
            {
                return;
            }
            if (!modifyDataResponse.Success)
            {
                ApiError.Throw(ApiErrorCode.InternalServerError, server, "Unable to update account info.");
                return;
            }
            GenericSuccessResponse successResponse       = new GenericSuccessResponse(ResponseId.UpdateAccountInfo, true);
            SerializedApiResponse  serializedApiResponse = SerializedApiResponse.Create(successResponse);
            string json = serializedApiResponse.Serialize();

            server.Send(json);
            server.UnitTesting.MethodSuccess = true;
        }