Пример #1
0
        private APIGatewayProxyResponse UpdateCharacterAssignRequest(opendkpContext pDatabase, string pClientId, UserRequests pUserRequest, CognitoUser pCognitoUser)
        {
            var vResponse = HttpHelper.HandleError("[UserRequestsLambda] Issue with DB or Query", 500);

            if (!string.IsNullOrWhiteSpace(pUserRequest.Requestor) && !string.IsNullOrWhiteSpace(pUserRequest.RequestDetails))
            {
                if (pUserRequest.RequestStatus == UserRequests.STATUS_APPROVED)
                {
                    dynamic vCharacterId = JsonConvert.DeserializeObject(pUserRequest.RequestDetails);
                    int     vId          = vCharacterId.characterId;

                    //I need to associate the character
                    //If character associate is successful, I need to update pending request to completed
                    using (var dbContextTransaction = pDatabase.Database.BeginTransaction())
                    {
                        UserXCharacter vAssociation = new UserXCharacter();
                        vAssociation.User        = pUserRequest.Requestor;
                        vAssociation.IdCharacter = vId;
                        vAssociation.ApprovedBy  = pCognitoUser.Username;
                        vAssociation.ClientId    = pClientId;
                        pDatabase.Add(vAssociation);

                        UserRequests vRequest = pDatabase.UserRequests.FirstOrDefault(x => x.ClientId.Equals(pClientId) && x.Id == pUserRequest.Id);
                        if (vRequest == null)
                        {
                            return(HttpHelper.HandleError("[UserRequestsLambda] Couldn't find the Request in DB to update...", 500));
                        }
                        vRequest.RequestApprover   = pCognitoUser.Username;
                        vRequest.ReviewedTimestamp = DateTime.Now;
                        vRequest.RequestStatus     = UserRequests.STATUS_APPROVED;
                        vRequest.ClientId          = pClientId;

                        pDatabase.SaveChanges();
                        dbContextTransaction.Commit();
                        vResponse = HttpHelper.HandleResponse(vRequest, 200, true);
                    }
                }
                else if (pUserRequest.RequestStatus == UserRequests.STATUS_DENIED)
                {
                    UserRequests vRequest = pDatabase.UserRequests.FirstOrDefault(x => x.ClientId.Equals(pClientId) && x.Id == pUserRequest.Id);
                    if (vRequest == null)
                    {
                        return(HttpHelper.HandleError("[UserRequestsLambda] Couldn't find the Request in DB to update...", 500));
                    }
                    vRequest.RequestApprover   = pCognitoUser.Username;
                    vRequest.ReviewedTimestamp = DateTime.Now;
                    vRequest.RequestStatus     = UserRequests.STATUS_DENIED;
                    vRequest.RequestDetails    = pUserRequest.RequestDetails;
                    vRequest.ClientId          = pClientId;

                    pDatabase.SaveChanges();
                    vResponse = HttpHelper.HandleResponse(vRequest, 200, true);
                }
            }
            return(vResponse);
        }
Пример #2
0
        /// <summary>
        /// Set the cache value for a particular cache
        /// </summary>
        /// <param name="pContext">The database context in which to set the cache in</param>
        /// <param name="pCacheName">The name of the cache you are storing, case-insensitive</param>
        /// <param name="pCacheValue">The value to be stored for this cache</param>
        /// <param name="pCacheExpires">The time the cache should expire</param>
        public static void SetCache(opendkpContext pContext, string pCacheName, string pCacheValue, string pClientId, DateTime?pCacheExpires = null)
        {
            if (pCacheExpires == null)
            {
                pCacheExpires = DateTime.Now.AddHours(12);
            }
            try
            {
                Cache vCachedSummary = pContext.Cache.FirstOrDefault(x => x.ClientId.Equals(pClientId) && x.CacheName.Equals(pCacheName, StringComparison.InvariantCultureIgnoreCase));
                if (vCachedSummary == null)
                {
                    vCachedSummary = new Cache {
                        CacheName = pCacheName,
                        ClientId  = pClientId
                    };
                    pContext.Add <Cache>(vCachedSummary);
                }
                vCachedSummary.CacheUpdated = DateTime.Now;
                vCachedSummary.CacheExpires = DateTime.Now.AddHours(12);
                vCachedSummary.CacheValue   = pCacheValue;

                pContext.SaveChanges();
            }
            catch (Exception vException)
            {
                Console.WriteLine("Error Cacheing: " + vException);
            }
        }
Пример #3
0
        /// <summary>
        /// Creates an item into the db if needed (not found already)
        /// </summary>
        /// <param name="pDBContext">The database context in which to look or create the item in</param>
        /// <param name="pItem">The item to create or lookup, checks for its Id first otherwise by name</param>
        /// <returns></returns>
        public static Items CreateItemIfNeeded(opendkpContext pDBContext, Items pItem)
        {
            Items vFoundItem = pDBContext.Items.FirstOrDefault <Items>(x => x.IdItem == pItem.IdItem);

            //If we don't find the item by it's ID
            if (vFoundItem == null)
            {
                vFoundItem = pDBContext.Items
                             .FirstOrDefault <Items>(x => x.Name.Trim().Equals(pItem.Name.Trim(), StringComparison.InvariantCultureIgnoreCase));

                //If we don't find the item by it's name
                if (vFoundItem == null)
                {
                    var vNewItem = new Items
                    {
                        Name = pItem.Name
                    };
                    pDBContext.Add(vNewItem);
                    pDBContext.SaveChanges();
                    vFoundItem = vNewItem;
                }
            }

            return(vFoundItem);
        }
Пример #4
0
        /// <summary>
        /// As the name suggests, creates a character if they are needed. Need is determined by whether or not they already exist in the database
        /// </summary>
        /// <param name="pDBContext">The database context to search for the character</param>
        /// <param name="pCharacterName">The character name to search for, case-insensitive</param>
        /// <returns></returns>
        public static Characters CreateCharacterIfNeeded(opendkpContext pDBContext, string pClientId, string pCharacterName)
        {
            Characters vCharacterModel = pDBContext.Characters
                                         .FirstOrDefault(x => x.Name.Equals(pCharacterName, StringComparison.InvariantCultureIgnoreCase));

            //If the character doesn't exist, we need to create a blank one first
            if (vCharacterModel == null)
            {
                vCharacterModel = new Characters
                {
                    Name     = char.ToUpper(pCharacterName[0]) + pCharacterName.Substring(1),
                    Class    = "UNKNOWN",
                    Race     = "UNKNOWN",
                    Active   = 1,
                    Rank     = "Inactive",
                    Level    = 1,
                    Gender   = "Male",
                    Guild    = "Original Gangster Club",
                    ClientId = pClientId
                };
                pDBContext.Add(vCharacterModel);
                pDBContext.SaveChanges();
            }

            return(vCharacterModel);
        }
Пример #5
0
        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="pInput">Incoming API Gateway request object, used to pull parameter from url</param>
        /// <param name="pContext">Incoming Lambda Context object, not used currently</param>
        /// <returns></returns>
        public void FunctionHandler(string pInput, ILambdaContext pContext)
        {
            try
            {
                using (opendkpContext vDatabase = new opendkpContext())
                {
                    var vChanges    = new Dictionary <string, string>();
                    var vCharacters = vDatabase.Characters.Include("TicksXCharacters.IdTickNavigation.Raid");
                    foreach (Characters vCharacter in vCharacters)
                    {
                        var vTickCount = vCharacter.TicksXCharacters.Where(x => DateTime.Compare(x.IdTickNavigation.Raid.Timestamp.Date,
                                                                                                 DateTime.Now.AddDays(-60).Date) >= 0).Count();

                        if (vTickCount > 0 && vCharacter.Active == 0)
                        {
                            vCharacter.Active = 1;
                            Console.WriteLine(string.Format("{0} Marked ACTIVE, Total Ticks = {1}", vCharacter.Name, vTickCount));
                            vChanges.Add(vCharacter.Name, "Marked Active, Total Ticks = " + vTickCount);
                        }
                        if (vTickCount <= 0 && vCharacter.Active == 1)
                        {
                            vCharacter.Active = 0;
                            Console.WriteLine(string.Format("{0} Marked INACTIVE, Total Ticks = {1}", vCharacter.Name, vTickCount));
                            vChanges.Add(vCharacter.Name, "Marked Inactive, Total Ticks = " + vTickCount);
                        }
                    }
                    vDatabase.SaveChanges();
                }
            }
            catch (Exception vException)
            {
                Console.WriteLine(vException);
            }
        }
Пример #6
0
        private APIGatewayProxyResponse HandleInsert(APIGatewayProxyRequest pRequest, ILambdaContext pContext, CognitoUser pCognitoUser, opendkpContext pDatabase, string pClientId)
        {
            var vResponse = HttpHelper.HandleError("[Insert] Unknown error backend...", 500);

            try
            {
                Characters vModel = JsonConvert.DeserializeObject <Characters>(pRequest.Body);
                if (vModel != null)
                {
                    Characters vExists = pDatabase.Characters.FirstOrDefault(x => x.ClientId.Equals(pClientId) &&
                                                                             x.Name.Equals(vModel.Name, StringComparison.InvariantCultureIgnoreCase));
                    if (vExists != null && vExists.IdCharacter >= 0)
                    {
                        vResponse = HttpHelper.HandleError("Character found in database, can't duplicate. Character Name must be unique", 500);
                    }
                    else
                    {
                        //Enforce ClientId serverside, don't trust what the client sends us
                        vModel.ClientId = pClientId;

                        pDatabase.Add(vModel);
                        pDatabase.SaveChanges();
                        AuditHelper.InsertAudit(pDatabase, pClientId, string.Empty, vModel, pCognitoUser.Username, Audit.ACTION_CHAR_INSERT);
                        vResponse = HttpHelper.HandleResponse(vModel, 200, true);
                    }
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError(vException.Message, 500);
            }

            return(vResponse);
        }
Пример #7
0
        private APIGatewayProxyResponse HandleInsert(APIGatewayProxyRequest pRequest, ILambdaContext pContext, CognitoUser pCognitoUser, opendkpContext pDatabase)
        {
            var vResponse = HttpHelper.HandleError("[InsertOrUpdateAdjustment] Unknown error backend...", 500);
            //We need to retrieve the ClientId for multitenancy purposes
            var vClientId = pRequest.Headers["clientid"];

            try
            {
                //Populate Model
                dynamic vModel           = JsonConvert.DeserializeObject(pRequest.Body);
                string  vInputCharacters = (string)vModel.Character;
                vInputCharacters = vInputCharacters.Trim();

                string[] vCharacterList = vInputCharacters.Split(',');

                using (var dbContextTransaction = pDatabase.Database.BeginTransaction())
                {
                    foreach (string vCharacter in vCharacterList)
                    {
                        //Create our Adjustment for each Character
                        Adjustments vAdjustment = new Adjustments
                        {
                            Name        = vModel.Name,
                            Description = vModel.Description,
                            Value       = vModel.Value,
                            Timestamp   = vModel.Timestamp,
                            ClientId    = vClientId
                        };

                        //Convert Character Name to Character Id
                        vAdjustment.IdCharacter = DkpConverters.CharacterNameToId(pDatabase, vClientId, vCharacter);
                        if (vAdjustment != null && vAdjustment.IdCharacter > -1)
                        {
                            pDatabase.Add(vAdjustment);
                            pDatabase.SaveChanges();
                        }
                    }
                    //Commit changes to DB
                    dbContextTransaction.Commit();
                    //Create success response
                    vResponse = HttpHelper.HandleResponse(vModel, 200);

                    //Audit
                    AuditHelper.InsertAudit(pDatabase, vClientId, string.Empty, vModel, pCognitoUser.Username, Audit.ACTION_ADJUST_INSERT);

                    //Update Caches
                    int vStatus = CacheManager.UpdateSummaryCacheAsync(vClientId).GetAwaiter().GetResult();
                    Console.WriteLine("StatusCode for CacheUpdate=" + vStatus);
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError(vException.Message, 500);
            }

            return(vResponse);
        }
Пример #8
0
        /// <summary>
        /// Lambda to insert character to character table
        /// </summary>
        /// <param name="pRequest">Incoming API Gateway request object, should be a PUT or POST with a BODY</param>
        /// <param name="pContext">Incoming Lambda Context object, not used currently</param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest pRequest, ILambdaContext pContext)
        {
            if (pRequest.Headers.Keys.Contains("warmup"))
            {
                return(HttpHelper.WarmupResponse());
            }
            var vResponse = HttpHelper.HandleError("[DeleteAdjustment] Unknown Backend error", 500);

            try
            {
                if (pRequest != null && pRequest.PathParameters != null && pRequest.PathParameters.Count > 0)
                {
                    int vId = int.Parse(pRequest.PathParameters["id"]);
                    using (opendkpContext vDatabase = new opendkpContext())
                    {
                        //Authorized Users only for Deleting Adjustments
                        if (!CognitoHelper.IsDkpAdmin(pRequest) ||
                            !CognitoHelper.IsAuthorizedAdmin(vDatabase, pRequest))
                        {
                            return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                        }
                        var vCognitoUser = CognitoHelper.GetCognitoUser(pRequest.Headers["cognitoinfo"]);

                        //We need to retrieve the ClientId for multitenancy purposes
                        var vClientId = pRequest.Headers["clientid"];

                        var vResult = vDatabase.Adjustments
                                      .FirstOrDefault(x => x.ClientId.Equals(vClientId) && x.IdAdjustment == vId);
                        if (vResult != null)
                        {
                            vDatabase.Adjustments.Remove(vResult);
                            vDatabase.SaveChanges();

                            //Audit
                            AuditHelper.InsertAudit(vDatabase, vClientId, vResult, string.Empty, vCognitoUser.Username, Audit.ACTION_ADJUST_DELETE);

                            //Update Caches
                            int vStatus = CacheManager.UpdateSummaryCacheAsync(vClientId).GetAwaiter().GetResult();
                            Console.WriteLine("StatusCode for CacheUpdate=" + vStatus);

                            vResponse = HttpHelper.HandleResponse(vResult, 200, true);
                        }
                        else
                        {
                            vResponse = HttpHelper.HandleError("[DeleteAdjustment] Adjustment doesnt exist in DB", 500);
                        }
                    }
                }
            }
            catch
            {
                vResponse = HttpHelper.HandleError("[DeleteAdjustment] Issue with DB or Query", 500);
            }

            return(vResponse);
        }
Пример #9
0
        /// <summary>
        /// Lambda to insert character to character table
        /// </summary>
        /// <param name="pRequest">Incoming API Gateway request object, should be a PUT or POST with a BODY</param>
        /// <param name="pContext">Incoming Lambda Context object, not used currently</param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest pRequest, ILambdaContext pContext)
        {
            if (pRequest.Headers.Keys.Contains("warmup"))
            {
                return(HttpHelper.WarmupResponse());
            }
            var vResponse = HttpHelper.HandleError("[DeleteCharacter] Unknown Backend error", 500);

            try
            {
                if (pRequest != null && pRequest.PathParameters != null && pRequest.PathParameters.Count > 0)
                {
                    //We need to retrieve the ClientId for multitenancy purposes
                    var vClientId = pRequest.Headers["clientid"];

                    string vCharacterName = pRequest.PathParameters["character"];
                    using (opendkpContext vDatabase = new opendkpContext())
                    {
                        //Authorized Users only for Deleting Characters
                        if (!CognitoHelper.IsDkpAdmin(pRequest) ||
                            !CognitoHelper.IsAuthorizedAdmin(vDatabase, pRequest))
                        {
                            return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                        }
                        var vCognitoUser = CognitoHelper.GetCognitoUser(pRequest.Headers["cognitoinfo"]);

                        var vResult = vDatabase.
                                      Characters.
                                      FirstOrDefault(x => x.ClientId.Equals(vClientId) &&
                                                     x.Name.Equals(vCharacterName, StringComparison.InvariantCultureIgnoreCase));

                        if (vResult != null)
                        {
                            vDatabase.Characters.Remove(vResult);
                            vDatabase.SaveChanges();
                            AuditHelper.InsertAudit(vDatabase, vClientId, vResult, string.Empty, vCognitoUser.Username, Audit.ACTION_CHAR_DELETE);
                            vResponse = HttpHelper.HandleResponse(vResult, 200);
                        }
                        else
                        {
                            vResponse = HttpHelper.HandleError("[DeleteCharacter] Character doesn't exist in the DB", 500);
                        }
                    }
                }
            }
            catch
            {
                vResponse = HttpHelper.HandleError("[DeleteCharacter] Issue with DB or Query", 500);
            }

            return(vResponse);
        }
Пример #10
0
        private APIGatewayProxyResponse HandleUpdateAsync(APIGatewayProxyRequest pRequest, ILambdaContext pContext, CognitoUser pCognitoUser, opendkpContext pDatabase)
        {
            var vResponse = HttpHelper.HandleError("[InsertOrUpdateAdjustment] Unknown error backend...", 500);
            //We need to retrieve the ClientId for multitenancy purposes
            var vClientId = pRequest.Headers["clientid"];

            try
            {
                //Populate Model
                dynamic     vModel      = JsonConvert.DeserializeObject(pRequest.Body);
                Adjustments vAdjustment = new Adjustments()
                {
                    Name         = vModel.Name,
                    Description  = vModel.Description,
                    Value        = vModel.Value,
                    Timestamp    = vModel.Timestamp,
                    IdAdjustment = vModel.Id,
                    ClientId     = vClientId
                };
                int vId = vModel.Id;
                if (vAdjustment != null)
                {
                    Adjustments vExists = pDatabase.Adjustments
                                          .FirstOrDefault(x => x.ClientId.Equals(vClientId) && x.IdAdjustment == vId);
                    string vOld = JsonConvert.SerializeObject(vExists, new JsonSerializerSettings {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    });

                    vAdjustment.IdCharacter = vExists.IdCharacter;
                    pDatabase.Entry(vExists).CurrentValues.SetValues(vAdjustment);
                    pDatabase.SaveChanges();
                    vResponse = HttpHelper.HandleResponse(vModel, 200);

                    //Audit
                    AuditHelper.InsertAudit(pDatabase, vClientId, vOld, pRequest.Body, pCognitoUser.Username, Audit.ACTION_ADJUST_UPDATE);

                    //Update Caches
                    int vStatus = CacheManager.UpdateSummaryCacheAsync(vClientId).GetAwaiter().GetResult();
                    Console.WriteLine("StatusCode for CacheUpdate=" + vStatus);
                }
            }
            catch (Exception vException)
            {
                Console.WriteLine("1 Exception: " + vException);
                vResponse = HttpHelper.HandleError(vException.Message, 500);
            }
            return(vResponse);
        }
Пример #11
0
        /// <summary>
        /// Lambda to insert character to character table
        /// </summary>
        /// <param name="pRequest">Incoming API Gateway request object, should be a PUT or POST with a BODY</param>
        /// <param name="pContext">Incoming Lambda Context object, not used currently</param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest pRequest, ILambdaContext pContext)
        {
            if (pRequest.Headers.Keys.Contains("warmup"))
            {
                return(HttpHelper.WarmupResponse());
            }
            var vResponse = HttpHelper.HandleError("[DeleteRaid] Unknown Backend error", 500);

            try
            {
                if (pRequest != null && pRequest.PathParameters != null && pRequest.PathParameters.Count > 0)
                {
                    int vId = int.Parse(pRequest.PathParameters["id"]);
                    using (opendkpContext vDatabase = new opendkpContext())
                    {
                        //Authorized Users only for Deleting Raids
                        if (!CognitoHelper.IsDkpAdmin(pRequest) ||
                            !CognitoHelper.IsAuthorizedAdmin(vDatabase, pRequest))
                        {
                            return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                        }
                        var vCognitoUser = CognitoHelper.GetCognitoUser(pRequest.Headers["cognitoinfo"]);

                        //We need to retrieve the ClientId for multitenancy purposes
                        var vClientId = pRequest.Headers["clientid"];

                        Raids vResult = RaidHelper.DeleteRaid(vDatabase, vId, vClientId);
                        vDatabase.SaveChanges();
                        vResponse = HttpHelper.HandleResponse(vResult, 200);

                        //Audit
                        AuditHelper.InsertAudit(vDatabase, vClientId, vResult, string.Empty, vCognitoUser.Username, Audit.ACTION_RAID_DELETE);

                        //Update Caches
                        int vStatus = CacheManager.UpdateSummaryCacheAsync(vClientId).GetAwaiter().GetResult();
                        Console.WriteLine("SummaryCacheResponse=" + vStatus);
                        vStatus = CacheManager.UpdateItemCacheAsync(vClientId).GetAwaiter().GetResult();
                        Console.WriteLine("ItemCacheResponse=" + vStatus);
                    }
                }
            }
            catch
            {
                vResponse = HttpHelper.HandleError("[DeleteRaid] Issue with DB or Query", 500);
            }

            return(vResponse);
        }
Пример #12
0
        /// <summary>
        /// Deletes a UserRequest from the Database
        /// </summary>
        /// <param name="pDBContext">The database in which to delete the UserREquest from</param>
        /// <param name="pRequest">The UserRequest to delete</param>
        /// <returns></returns>
        public static bool DeleteRequest(opendkpContext pDBContext, UserRequests pRequest)
        {
            bool vReturn = false;

            try
            {
                pDBContext.Remove(pRequest);
                pDBContext.SaveChanges();
                vReturn = true;
            }
            catch (Exception vException)
            {
                Console.WriteLine("Error Inserting AdminRequest: " + vException);
            }
            return(vReturn);
        }
Пример #13
0
        private APIGatewayProxyResponse HandleCharacterAssignRequest(opendkpContext pDatabase, UserRequests pUserRequest, APIGatewayProxyRequest pRequest, CognitoUser pCognitoUser)
        {
            var vResponse = HttpHelper.HandleError("[UserRequestsLambda] Issue with DB or Query", 500);

            //We need to retrieve the ClientId for multitenancy purposes
            var vClientId = pRequest.Headers["clientid"];

            if (!string.IsNullOrWhiteSpace(pUserRequest.RequestDetails))
            {
                dynamic vCharacterId = JsonConvert.DeserializeObject(pUserRequest.RequestDetails);
                int     vId          = vCharacterId.characterId;

                //Determine if we've already got a character associated for this character Id
                var vFound = pDatabase.UserXCharacter.FirstOrDefault(x => x.ClientId.Equals(vClientId) && x.IdCharacter == vId);
                if (vFound != null)
                {
                    return(HttpHelper.HandleError("[UserRequestsLambda] This character has already been associated to an account", 500));
                }

                //Verify that there is not already an open pending request for the specific character
                //Note: It's possible someone else tries to claim someone elses character and this request would block them
                //TODO: Review note above, determine if anything should be done regarding this scenario
                var vPendingRequests = pDatabase.UserRequests.Where(x => x.ClientId.Equals(vClientId) &&
                                                                    x.RequestType == UserRequests.TYPE_CHARACTER_ASSIGN &&
                                                                    x.RequestStatus == UserRequests.STATUS_PENDING).ToList();
                foreach (var vRequest in vPendingRequests)
                {
                    dynamic vTmpCharId = JsonConvert.DeserializeObject(vRequest.RequestDetails);
                    int     vTmpId     = vTmpCharId.characterId;
                    if (vTmpId == vId)
                    {
                        return(HttpHelper.HandleError("[UserRequestsLambda] There is already a pending request for this character", 500));
                    }
                }
                pUserRequest.Requestor         = pCognitoUser.Username;
                pUserRequest.RequestStatus     = UserRequests.STATUS_PENDING;
                pUserRequest.RequestTimestamp  = DateTime.Now;
                pUserRequest.RequestApprover   = "NONE";
                pUserRequest.ReviewedTimestamp = DateTime.Now;
                pUserRequest.ClientId          = vClientId;
                pDatabase.Add(pUserRequest);
                pDatabase.SaveChanges();
                vResponse = HttpHelper.HandleResponse(pUserRequest, 200, true);
            }
            return(vResponse);
        }
Пример #14
0
        /// <summary>
        /// Creates a raid Id, probably isn't needed anymore but early on in development I needed to get the RaidID first. 99.99% sure this isn't needed anymore but no time to refactor
        /// </summary>
        /// <param name="pDBContext">The database context to create the raid id in</param>
        /// <param name="pModel">The model containing the raid information to generate the id</param>
        /// <returns></returns>
        public static int CreateRaidId(opendkpContext pDBContext, string pClientId, dynamic pModel)
        {
            //Insert the raid first to get the RaidId
            Raids vRaid = new Raids()
            {
                Name             = pModel.Name,
                Timestamp        = pModel.Timestamp,
                IdPool           = pModel.Pool.IdPool,
                UpdatedBy        = pModel.UpdatedBy,
                UpdatedTimestamp = pModel.UpdatedTimestamp,
                ClientId         = pClientId
            };

            pDBContext.Add(vRaid);
            pDBContext.SaveChanges();
            //Set Raid Id to the Model we return to client for future updates
            return(vRaid.IdRaid);
        }
Пример #15
0
 /// <summary>
 /// Insert an audit entry into the audit table. This function will store the text passed in
 /// </summary>
 /// <param name="pDBContext">The database context to which the audit will be stored</param>
 /// <param name="pOldModel">A string representing an old value (changed from)</param>
 /// <param name="pNewModel">A string representing a new value (changed to)</param>
 /// <param name="pUsername">The username who made the change</param>
 /// <param name="pAction">The action being performed</param>
 public static void InsertAudit(opendkpContext pDBContext, string pClientId, string pOldModel, string pNewModel, string pUsername, string pAction)
 {
     try
     {
         Audit vAudit = new Audit
         {
             OldValue    = pOldModel,
             NewValue    = pNewModel,
             Timestamp   = DateTime.Now,
             CognitoUser = pUsername,
             Action      = pAction,
             ClientId    = pClientId
         };
         pDBContext.Add(vAudit);
         pDBContext.SaveChanges();
     }
     catch (Exception vException)
     {
         Console.WriteLine("Failed to log audit for some reason");
         Console.WriteLine(vException);
     }
 }
Пример #16
0
        private APIGatewayProxyResponse HandleUpdate(APIGatewayProxyRequest pRequest, ILambdaContext pContext, CognitoUser pCognitoUser, opendkpContext pDatabase, string pClientId)
        {
            var vResponse = HttpHelper.HandleError("[Update] Unknown error backend...", 500);

            try
            {
                Characters vModel = JsonConvert.DeserializeObject <Characters>(pRequest.Body);
                if (vModel != null)
                {
                    Characters vExists = pDatabase.Characters.FirstOrDefault(x => x.ClientId.Equals(pClientId) &&
                                                                             x.IdCharacter == vModel.IdCharacter);
                    if (vExists != null && vExists.IdCharacter >= 0)
                    {
                        string vOld = JsonConvert.SerializeObject(vExists,
                                                                  new JsonSerializerSettings {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });

                        //CustomCharacter class is a subset model of Characters, design to update only specific properties
                        CharacterModel vSimplifiedModel = new CharacterModel(vModel);
                        pDatabase.Entry(vExists).CurrentValues.SetValues(vSimplifiedModel);
                        pDatabase.SaveChanges();
                        AuditHelper.InsertAudit(pDatabase, pClientId, vOld, pRequest.Body, pCognitoUser.Username, Audit.ACTION_CHAR_UPDATE);
                        vResponse = HttpHelper.HandleResponse(vSimplifiedModel, 200);
                    }
                    else
                    {
                        vResponse = HttpHelper.HandleError("Character not found in database", 500);
                    }
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError(vException.Message, 500);
            }
            return(vResponse);
        }
Пример #17
0
        private APIGatewayProxyResponse HandleInsert(APIGatewayProxyRequest pRequest, ILambdaContext pContext, CognitoUser pCognitoUser, opendkpContext pDatabase)
        {
            var vResponse = HttpHelper.HandleError("[InsertOrUpdateRaid] Unknown error backend...", 500);
            //We need to retrieve the ClientId for multitenancy purposes
            var vClientId = pRequest.Headers["clientid"];

            try
            {
                //Populate Model
                dynamic vModel = JsonConvert.DeserializeObject(pRequest.Body);
                using (var dbContextTransaction = pDatabase.Database.BeginTransaction())
                {
                    Dictionary <string, Characters> vCharacterModels = RaidHelper.GetCharacterModels(pDatabase, vClientId, vModel);

                    vModel.IdRaid = RaidHelper.CreateRaidId(pDatabase, vClientId, vModel);
                    RaidHelper.InsertRaidItems(pDatabase, vClientId, vModel, vCharacterModels);
                    RaidHelper.InsertRaidTicks(pDatabase, vClientId, vModel, vCharacterModels);
                    pDatabase.SaveChanges();
                    dbContextTransaction.Commit();

                    vResponse = HttpHelper.HandleResponse(vModel, 200);
                    AuditHelper.InsertAudit(pDatabase, vClientId, string.Empty, vModel, pCognitoUser.Username, Audit.ACTION_RAID_INSERT);

                    //Update Caches
                    int vStatus = CacheManager.UpdateSummaryCacheAsync(vClientId).GetAwaiter().GetResult();
                    Console.WriteLine("SummaryCacheResponse=" + vStatus);
                    vStatus = CacheManager.UpdateItemCacheAsync(vClientId).GetAwaiter().GetResult();
                    Console.WriteLine("ItemCacheResponse=" + vStatus);
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError(vException.Message, 500);
            }

            return(vResponse);
        }
Пример #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pRequest">Incoming API Gateway request object, not used currently</param>
        /// <param name="pContext">Incoming Lambda Context object, not used currently</param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest pRequest, ILambdaContext pContext)
        {
            if (pRequest.Headers != null && pRequest.Headers.Count > 0 && pRequest.Headers.Keys.Contains("warmup"))
            {
                return(HttpHelper.WarmupResponse());
            }
            var vResponse = HttpHelper.HandleError("[AdminSettings] Unknown Error in backend", 500);
            //We need to retrieve the ClientId for multitenancy purposes
            var vClientId = pRequest.Headers["clientid"];

            try
            {
                using (opendkpContext vDatabase = new opendkpContext())
                {
                    if (pRequest.HttpMethod == "GET")
                    {
                        string vSettingName = pRequest.PathParameters["setting"];
                        var    vResult      = vDatabase.AdminSettings.Where(x => x.ClientId.Equals(vClientId) && x.SettingName.Equals(vSettingName,
                                                                                                                                      StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                        if (vResult == null)
                        {
                            vResult = new AdminSettings();
                        }
                        return(HttpHelper.HandleResponse(JsonConvert.SerializeObject(vResult), 200));
                    }
                    //This is the Guild Dump Utility I quickly wrote
                    if (pRequest.HttpMethod == "POST")
                    {
                        //Authorize User for POST requests only
                        if (!CognitoHelper.IsDkpAdmin(pRequest) ||
                            !CognitoHelper.IsAuthorizedAdmin(vDatabase, pRequest))
                        {
                            return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                        }

                        //Process Guild Dump
                        dynamic vModel  = JsonConvert.DeserializeObject(pRequest.Body);
                        string  vAction = vModel.Action;
                        JArray  vData   = vModel.Data;
                        if (!string.IsNullOrWhiteSpace(vAction))
                        {
                            var           vCharacters     = vData.ToObject <Characters[]>();
                            List <string> vCharacterNames = new List <string>();
                            foreach (Characters vCharacter in vCharacters)
                            {
                                vCharacterNames.Add(vCharacter.Name);
                            }
                            var vResults = vDatabase.Characters.Where(x => x.ClientId.Equals(vClientId) && vCharacterNames.Contains(x.Name));
                            foreach (var item in vResults)
                            {
                                var vChar = vCharacters.FirstOrDefault(x => x.Name.Equals(item.Name));
                                if (vChar != null)
                                {
                                    item.Level = vChar.Level;
                                    item.Rank  = vChar.Rank;
                                    item.Class = vChar.Class;
                                }
                            }
                            vDatabase.SaveChanges();
                            return(HttpHelper.HandleResponse("Success", 200));
                        }
                        else
                        {
                            AdminSettings vInputModel = JsonConvert.DeserializeObject <AdminSettings>(pRequest.Body);
                            AdminSettings vAdminModel = vDatabase.AdminSettings
                                                        .FirstOrDefault(x => x.ClientId.Equals(vClientId) && x.SettingName.Equals(vInputModel.SettingName,
                                                                                                                                  StringComparison.InvariantCultureIgnoreCase));

                            if (vAdminModel == null)
                            {
                                vAdminModel          = vInputModel;
                                vAdminModel.ClientId = vClientId;
                                vDatabase.Add(vAdminModel);
                            }
                            vAdminModel.SettingValue     = vInputModel.SettingValue;
                            vAdminModel.UpdatedBy        = vInputModel.UpdatedBy;
                            vAdminModel.UpdatedTimestamp = vInputModel.UpdatedTimestamp;
                            vAdminModel.ClientId         = vClientId;
                            vDatabase.SaveChanges();
                            return(HttpHelper.HandleResponse(JsonConvert.SerializeObject(vAdminModel), 200));
                        }
                    }
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError("[AdminSettings] Error Connecting to DB: " + vException.Message, 500);
            }
            return(vResponse);
        }
Пример #19
0
        private APIGatewayProxyResponse HandleUpdate(APIGatewayProxyRequest pRequest, ILambdaContext pContext, CognitoUser pCognitoUser, opendkpContext pDatabase)
        {
            var vResponse = HttpHelper.HandleError("[InsertOrUpdateAdjustment] Unknown error backend...", 500);

            try
            {
                //Populate Model
                dynamic vModel  = JsonConvert.DeserializeObject(pRequest.Body);
                int     vIdRaid = vModel.IdRaid;
                //We need to retrieve the ClientId for multitenancy purposes
                var vClientId = pRequest.Headers["clientid"];


                Dictionary <string, Characters> vCharacterModels = RaidHelper.GetCharacterModels(pDatabase, vClientId, vModel);

                using (var dbContextTransaction = pDatabase.Database.BeginTransaction())
                {
                    Raids vRaid = pDatabase.Raids.
                                  Include("Ticks.TicksXCharacters").
                                  Include("ItemsXCharacters.Item").
                                  Include("ItemsXCharacters.Character").
                                  Include("IdPoolNavigation").
                                  FirstOrDefault(x => x.ClientId.Equals(vClientId) && x.IdRaid == vIdRaid);

                    dynamic vOldModel = GetAuditModel(vRaid);

                    //Update some attributes of the raid
                    vRaid.Name             = vModel.Name;
                    vRaid.Timestamp        = vModel.Timestamp;
                    vRaid.UpdatedTimestamp = DateTime.Now;
                    vRaid.UpdatedBy        = vModel.UpdatedBy;
                    vRaid.IdPool           = vModel.Pool.IdPool;
                    vRaid.ClientId         = vClientId;

                    //Three Cases to handle: Raid Tick Added, Raid Tick Removed, Raid Tick Updated
                    #region Handle Raid Tick Removed here
                    SimpleTick[] vSimpleTicks = vModel.Ticks.ToObject <SimpleTick[]>();
                    List <Ticks> vRemoveTicks = new List <Ticks>();
                    foreach (Ticks vIndex in vRaid.Ticks)
                    {
                        var vFound = vSimpleTicks.FirstOrDefault(x => x.TickId == vIndex.TickId);
                        if (vFound == null)
                        {
                            vRemoveTicks.Add(vIndex);
                        }
                    }
                    foreach (Ticks vTick in vRemoveTicks)
                    {
                        vRaid.Ticks.Remove(vTick);
                    }
                    #endregion
                    #region Handle Raid Tick Added & Raid Tick Updated Here
                    foreach (var vTick in vModel.Ticks)
                    {
                        int?vTickId = vTick.TickId;
                        //If tickId is null, we have to create an insert a new one
                        if (vTickId == null)
                        {
                            RaidHelper.CreateTick(pDatabase, vClientId, vRaid.IdRaid, vTick, vCharacterModels);
                        }
                        else
                        {
                            Ticks vFoundTick = vRaid.Ticks.FirstOrDefault(x => x.TickId == vTickId);
                            if (vFoundTick != null)
                            {
                                vFoundTick.Description = vTick.Description;
                                vFoundTick.Value       = vTick.Value;
                                vFoundTick.ClientId    = vClientId;

                                //Now that I've found the tick
                                vFoundTick.TicksXCharacters = new List <TicksXCharacters>();
                                foreach (string vAttendee in vTick.Attendees)
                                {
                                    vFoundTick.TicksXCharacters.Add(new TicksXCharacters
                                    {
                                        IdCharacterNavigation = vCharacterModels[vAttendee.ToLower()],
                                        IdTickNavigation      = vFoundTick,
                                        ClientId = vClientId
                                    });
                                }
                            }
                            else
                            {
                                throw new Exception(string.Format("The tick id {0} does not exist, will not save raid", vTickId));
                            }
                        }
                    }
                    #endregion

                    //Handle Items
                    vRaid.ItemsXCharacters = new List <ItemsXCharacters>();
                    RaidHelper.InsertRaidItems(pDatabase, vClientId, vModel, vCharacterModels);

                    //Save
                    pDatabase.SaveChanges();
                    dbContextTransaction.Commit();

                    //Respond
                    vResponse = HttpHelper.HandleResponse(vModel, 200);

                    //Audit
                    AuditHelper.InsertAudit(pDatabase, vClientId, vOldModel, vModel, pCognitoUser.Username, Audit.ACTION_RAID_UPDATE);

                    //Update Caches
                    int vStatus = CacheManager.UpdateSummaryCacheAsync(vClientId).GetAwaiter().GetResult();
                    Console.WriteLine("SummaryCacheResponse=" + vStatus);
                    vStatus = CacheManager.UpdateItemCacheAsync(vClientId).GetAwaiter().GetResult();
                    Console.WriteLine("ItemCacheResponse=" + vStatus);
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError(vException.Message, 500);
            }

            return(vResponse);
        }
Пример #20
0
        private APIGatewayProxyResponse UpdateRaidTickRequest(opendkpContext pDatabase, UserRequests pUserRequest, CognitoUser pCognitoUser, string pClientId)
        {
            var vResponse = HttpHelper.HandleError("[UserRequestsLambda] Issue with DB or Query", 500);

            if (!string.IsNullOrWhiteSpace(pUserRequest.Requestor) && !string.IsNullOrWhiteSpace(pUserRequest.RequestDetails))
            {
                if (pUserRequest.RequestStatus == UserRequests.STATUS_APPROVED)
                {
                    dynamic vModel = JsonConvert.DeserializeObject(pUserRequest.RequestDetails);
                    //`{characterName:${this.CharacterName},tickId=${this.SelectedData.TickId},reason:${this.LogData}}`;
                    string vCharacterName = vModel.characterName;
                    int    vTickId        = vModel.tickId;
                    string vReason        = vModel.reason;

                    //I need to associate the character
                    //If character associate is successful, I need to update pending request to completed
                    using (var dbContextTransaction = pDatabase.Database.BeginTransaction())
                    {
                        //First, lets make sure the Character Exists in the Database!
                        Characters vCharacter = CharacterHelper.GetCharacterByName(pDatabase, pClientId, vCharacterName);
                        if (vCharacter == null)
                        {
                            return(HttpHelper.HandleError(string.Format("{0} does not exist in the database...", vCharacterName), 500));
                        }

                        //Determine if this character already has the raid tick
                        var vFound = pDatabase.TicksXCharacters.FirstOrDefault(x => x.ClientId.Equals(pClientId) && x.IdCharacter == vCharacter.IdCharacter && x.IdTick == vTickId);
                        if (vFound != null)
                        {
                            return(HttpHelper.HandleError("You already have credit for this raid tick!", 500));
                        }

                        TicksXCharacters vTickToInsert = new TicksXCharacters();
                        vTickToInsert.IdCharacter = vCharacter.IdCharacter;
                        vTickToInsert.IdTick      = vTickId;
                        vTickToInsert.ClientId    = pClientId;
                        pDatabase.Add(vTickToInsert);

                        //Update the Request
                        UserRequests vRequest = pDatabase.UserRequests.FirstOrDefault(x => x.ClientId.Equals(pClientId) && x.Id == pUserRequest.Id);
                        if (vRequest == null)
                        {
                            return(HttpHelper.HandleError("[UserRequestsLambda] Couldn't find the Request in DB to update...", 500));
                        }

                        vRequest.RequestApprover   = pCognitoUser.Username;
                        vRequest.ReviewedTimestamp = DateTime.Now;
                        vRequest.RequestStatus     = UserRequests.STATUS_APPROVED;
                        vRequest.ClientId          = pClientId;

                        pDatabase.SaveChanges();
                        dbContextTransaction.Commit();

                        //Update Caches
                        int vStatus = CacheManager.UpdateSummaryCacheAsync(pClientId).GetAwaiter().GetResult();
                        Console.WriteLine("SummaryCacheResponse=" + vStatus);
                        vResponse = HttpHelper.HandleResponse(vRequest, 200, true);
                    }
                }
                else if (pUserRequest.RequestStatus == UserRequests.STATUS_DENIED)
                {
                    UserRequests vRequest = pDatabase.UserRequests.FirstOrDefault(x => x.ClientId.Equals(pClientId) && x.Id == pUserRequest.Id);
                    if (vRequest == null)
                    {
                        return(HttpHelper.HandleError("[UserRequestsLambda] Couldn't find the Request in DB to update...", 500));
                    }
                    vRequest.RequestApprover   = pCognitoUser.Username;
                    vRequest.ReviewedTimestamp = DateTime.Now;
                    vRequest.RequestStatus     = UserRequests.STATUS_DENIED;
                    vRequest.RequestDetails    = pUserRequest.RequestDetails;
                    vRequest.ClientId          = pClientId;

                    pDatabase.SaveChanges();
                    vResponse = HttpHelper.HandleResponse(vRequest, 200, true);
                }
            }
            return(vResponse);
        }
Пример #21
0
        private APIGatewayProxyResponse HandleRaidTickRequest(opendkpContext pDatabase, UserRequests pUserRequest, APIGatewayProxyRequest pRequest, CognitoUser pCognitoUser)
        {
            var vResponse = HttpHelper.HandleError("[UserRequestsLambda] Issue with DB or Query", 500);
            //We need to retrieve the ClientId for multitenancy purposes
            var vClientId = pRequest.Headers["clientid"];

            if (!string.IsNullOrWhiteSpace(pUserRequest.RequestDetails))
            {
                dynamic vModel = JsonConvert.DeserializeObject(pUserRequest.RequestDetails);
                //`{characterName:${this.CharacterName},tickId=${this.SelectedData.TickId},reason:${this.LogData}}`;
                string vCharacterName = vModel.characterName;
                int    vTickId        = vModel.tickId;
                string vReason        = vModel.reason;

                //First, lets make sure the Character Exists in the Database!
                Characters vCharacter = CharacterHelper.GetCharacterByName(pDatabase, vClientId, vCharacterName);
                if (vCharacter == null)
                {
                    return(HttpHelper.HandleError(string.Format("{0} does not exist in the database...", vCharacterName), 500));
                }

                //Second, lets confirm the Character is associated with the Account
                var vUser = pDatabase.UserXCharacter.FirstOrDefault(x => x.ClientId.Equals(vClientId) && x.IdCharacter == vCharacter.IdCharacter && x.User.Equals(pCognitoUser.Username));
                if (vUser == null)
                {
                    return(HttpHelper.HandleError(string.Format("{0} is not associated with your account", vCharacterName), 500));
                }

                //Determine if this character already has the raid tick
                var vFound = pDatabase.TicksXCharacters.FirstOrDefault(x => x.ClientId.Equals(vClientId) && x.IdCharacter == vCharacter.IdCharacter && x.IdTick == vTickId);
                if (vFound != null)
                {
                    return(HttpHelper.HandleError("You already have credit for this raid tick!", 500));
                }

                //Verify that there is not already an open pending request
                var vPendingRequests = pDatabase.UserRequests.Where(x => x.ClientId.Equals(vClientId) &&
                                                                    x.RequestType == UserRequests.TYPE_RAIDTICK &&
                                                                    x.RequestStatus == UserRequests.STATUS_PENDING).ToList();
                foreach (var vRequest in vPendingRequests)
                {
                    dynamic vTmpModel = JsonConvert.DeserializeObject(vRequest.RequestDetails);
                    string  vTmpName  = vTmpModel.characterName;
                    int     vTmpId    = vTmpModel.tickId;
                    if (vTmpId == vTickId && vCharacterName.Trim().Equals(vTmpName.Trim(), StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(HttpHelper.HandleError("There is already a pending request for this character & raid tick!", 500));
                    }
                }

                pUserRequest.Requestor         = pCognitoUser.Username;
                pUserRequest.RequestStatus     = UserRequests.STATUS_PENDING;
                pUserRequest.RequestTimestamp  = DateTime.Now;
                pUserRequest.RequestApprover   = "NONE";
                pUserRequest.ReviewedTimestamp = DateTime.Now;
                pUserRequest.ClientId          = vClientId;
                pDatabase.Add(pUserRequest);
                pDatabase.SaveChanges();
                vResponse = HttpHelper.HandleResponse(pUserRequest, 200, true);
            }
            return(vResponse);
        }