Пример #1
0
        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                CognitoHelper cognitoHelper = new CognitoHelper();
                cognitoUser = await cognitoHelper.ValidateUser(txtusername.Text, txtpassword.Text);

                MessageBox.Show("Login successfully");
                Console.WriteLine(cognitoUser.Username);

                CognitoAWSCredentials credentials = cognitoUser.GetCognitoAWSCredentials(ConfigurationManager.AppSettings["FED_POOL_id"], new AppConfigAWSRegion().Region);
                StringBuilder         tokens      = new StringBuilder();

                tokens.Append("================Cognito Credentails==================\n");
                tokens.Append("Access Key - " + credentials.GetCredentials().AccessKey);
                tokens.Append("\nSecret - " + credentials.GetCredentials().SecretKey);
                tokens.Append("\nSession Token - " + credentials.GetCredentials().Token);
                tokens.Append("\nUseToken Token - " + credentials.GetCredentials().UseToken.ToString());
                Console.WriteLine(tokens.ToString());
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp);
                MessageBox.Show("Unable to validate the username and password");
            }
        }
Пример #2
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());
            }
            if (pRequest == null)
            {
                return(HttpHelper.HandleError("Request appears to be null", 500));
            }

            using (opendkpContext vDatabase = new opendkpContext())
            {
                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"];

                if (pRequest.HttpMethod.Equals("PUT", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(HandleInsert(pRequest, pContext, vCognitoUser, vDatabase, vClientId));
                }
                else if (pRequest.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(HandleUpdate(pRequest, pContext, vCognitoUser, vDatabase, vClientId));
                }
            }
            return(HttpHelper.HandleError("Only Methods PUT,POST are supported by this lamdba", 500));
        }
Пример #3
0
        private async void button4_Click(object sender, EventArgs e)
        {
            try
            {
                CognitoHelper helper = new CognitoHelper();

                /*var req = new Amazon.CognitoIdentityProvider.Model.UpdateUserAttributesRequest();
                 * req.AccessToken = cognitoUser.SessionTokens.AccessToken;
                 * var att1 = new Amazon.CognitoIdentityProvider.Model.AttributeType();
                 * var att2 = new Amazon.CognitoIdentityProvider.Model.AttributeType();
                 * att2.Name = "custom:test2";
                 * att1.Name = "custom:Attribut";
                 * att1.Value = textBox1.Text;
                 * att2.Value = textBox2.Text;
                 * req.UserAttributes.Add(att1);
                 * req.UserAttributes.Add(att2);
                 * var result = await helper.UpdateAttributes(req);*/
                var    bla = helper.getAttributes(cognitoUser).Result.UserAttributes;
                String ans = "";
                foreach (var a in bla)
                {
                    ans += a.Name + " : " + a.Value + Environment.NewLine;
                }
                MessageBox.Show(ans);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                MessageBox.Show("Some kind of error");
            }
        }
Пример #4
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 != null && pRequest.Headers.Count > 0 && pRequest.Headers.Keys.Contains("warmup"))
            {
                return(HttpHelper.WarmupResponse());
            }
            if (pRequest == null)
            {
                return(HttpHelper.HandleError("Request appears to be null", 500));
            }
            //For these operations, we should have the CognitoInfo user available to us
            //Authorized Users only for Deleting Raids
            using (opendkpContext vDatabase = new opendkpContext())
            {
                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"]);

                if (pRequest.HttpMethod.Equals("PUT", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(HandleInsert(pRequest, pContext, vCognitoUser, vDatabase));
                }
                else if (pRequest.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(HandleUpdateAsync(pRequest, pContext, vCognitoUser, vDatabase));
                }
            }

            return(HttpHelper.HandleError("Only Methods PUT,POST are supported by this lamdba", 500));
        }
Пример #5
0
 public SignInSignUp()
 {
     InitializeComponent();
     _cognitoHelper = new CognitoHelper();
     if (Application.Current.Properties.ContainsKey("User"))
     {
         EmailEntry.Text = (Application.Current.Properties["User"] as User).EmailAddress;
     }
 }
Пример #6
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);
        }
Пример #7
0
        /// <summary>
        /// Lambda to fetch all characters from the character table
        /// </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("[CognitoAPIs] Unknown Error in backend", 500);

            try
            {
                string pUserPool = string.Empty;
                //The request should be from an authorized user, if yes then also grab the UserPool for the associated client
                using (opendkpContext vDatabase = new opendkpContext())
                {
                    //Authorized Users only for Audit information
                    if (!CognitoHelper.IsDkpAdmin(pRequest) ||
                        !CognitoHelper.IsAuthorizedAdmin(vDatabase, pRequest))
                    {
                        return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                    }

                    //No validation on header because it's pre-performed above in the CognitoHelper
                    pUserPool = vDatabase.Clients.
                                FirstOrDefault(x => x.ClientId.Equals(pRequest.Headers["clientid"],
                                                                      StringComparison.InvariantCultureIgnoreCase)).UserPool;
                }

                if (pRequest.HttpMethod == "GET")
                {
                    Task <object> vTask = GetAllUsersAsync(pUserPool);
                    vResponse = HttpHelper.HandleResponse(vTask.Result, 200);
                }
                if (pRequest.HttpMethod == "POST")
                {
                    dynamic vModel  = JsonConvert.DeserializeObject(pRequest.Body);
                    string  vAction = vModel.Action;
                    string  vData   = vModel.Data;

                    if (vAction.Equals("add-admin"))
                    {
                        Task <string> vTask = AddDkpAdminAsync(vData, pUserPool);
                        vResponse = HttpHelper.HandleResponse(vTask.Result, 200);
                    }
                    else if (vAction.Equals("remove-admin"))
                    {
                        Task <string> vTask = RemoveDkpAdminAsync(vData, pUserPool);
                        vResponse = HttpHelper.HandleResponse(vTask.Result, 200);
                    }
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError("[CognitoAPIs] " + vException.Message, 500);
            }
            return(vResponse);
        }
Пример #8
0
        /// <summary>
        /// Lambda to fetch all characters from the character table
        /// </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("[AuditLambda] Unknown Error in backend", 500);

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

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

                    if (pRequest.HttpMethod.Equals("GET", StringComparison.InvariantCultureIgnoreCase))
                    {
                        List <Audit> vResult;
                        if (vId > -1)
                        {
                            vResult = vDatabase.Audit.Where(x => x.ClientId.Equals(vClientId) && x.Id == vId).ToList();
                        }
                        else
                        {
                            //We don't want to transmit a ton of data for fetching all audits
                            vResult = vDatabase.Audit.Where(x => x.ClientId.Equals(vClientId)).ToList();
                            foreach (Audit vItem in vResult)
                            {
                                vItem.NewValue = string.Empty;
                                vItem.OldValue = string.Empty;
                            }
                        }
                        vResponse = HttpHelper.HandleResponse(vResult, 200, true);
                    }
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError("[AuditLambda] " + vException.Message, 500);
            }
            return(vResponse);
        }
Пример #9
0
        private async void btnSignUp_Click(object sender, EventArgs e)
        {
            if (dropMonth.selectedValue == "MM" || dropDay.selectedValue == "DD" || dropYear.selectedValue == "YYYY")
            {
                lblBDError.Visible = true;
            }
            else if (lblUNError.Visible == false && lblEmailError.Visible == false && lblPWError.Visible == false)
            {
                CognitoHelper cognitoHelper = new CognitoHelper();

                try
                {
                    string birthday = dropYear.selectedValue + "-" + dropMonth.selectedValue + "-" + dropDay.selectedValue;
                    bool   success  = await cognitoHelper.SignUpUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, birthday);

                    if (success)
                    {
                        VerificationCode verificationCode      = new VerificationCode(txtUsername.Text);
                        Point            verificationcodePoint = new Point(281, 162);

                        verificationCode.Location = verificationcodePoint;
                        verificationCode.Show();
                        Program.home.Controls.Add(verificationCode);

                        this.Dispose();
                    }
                    else
                    {
                        MessageBox.Show("some unhandled error");
                    }
                }
                catch (Amazon.CognitoIdentityProvider.Model.UsernameExistsException)
                {
                    lblUNError.Visible = true;
                    lblUNError.Text    = "Username already exists";
                }
                catch (Amazon.CognitoIdentityProvider.Model.AliasExistsException)
                {
                    lblUNError.Visible = true;
                    lblUNError.Text    = "Username already exists";
                }
                catch (Amazon.CognitoIdentityProvider.Model.InvalidParameterException)
                {
                    lblEmailError.Visible = true;
                    lblEmailError.Text    = "Invalid email";
                }
                catch (Exception)
                {
                    lblUNError.Visible = true;
                    lblUNError.Text    = "Unhandled exception";
                }
            }
        }
Пример #10
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);
        }
Пример #11
0
        private async void btnupdatepass_Click(object sender, EventArgs e)
        {
            try
            {
                CognitoHelper helper = new CognitoHelper();
                await helper.UpdatePassword(txtusername.Text, txtcode.Text, txtnewpassword.Text);

                MessageBox.Show("Password updated.");
            }
            catch (Exception exp)
            {
                MessageBox.Show("Unable to update the password" + exp.Message);
            }
        }
Пример #12
0
        private async void Login_Click(object sender, RoutedEventArgs e)
        {
            CognitoHelper cognitoHelper = new CognitoHelper();

            ioioSetting.All.cognitoUser = await cognitoHelper.ValidateUser("atumm", "B@y7cgmc");

            Console.WriteLine(ioioSetting.All.cognitoUser.Username);
            string email = string.Empty;

            ioioSetting.All.cognitoUser.Attributes.TryGetValue("email", out email);
            GetUserResponse r = await cognitoHelper.GetUserInfo(ioioSetting.All.cognitoUser);

            Console.WriteLine(email);
        }
Пример #13
0
        private async void button1_Click(object sender, EventArgs e)
        {
            CognitoHelper cognitoHelper = new CognitoHelper();
            bool          success       = await cognitoHelper.VerifyAccessCode(lblusername.Text, txtcode.Text);

            if (success)
            {
                MessageBox.Show("Able to validate the access code");
                this.Close();
            }
            else
            {
                MessageBox.Show("Unable to validate the access code");
            }
        }
Пример #14
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);
        }
Пример #15
0
        private async void button1_Click(object sender, EventArgs e)
        {
            CognitoHelper helper  = new CognitoHelper();
            bool          success = await helper.SignUpUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtPhone.Text);

            if (success)
            {
                MessageBox.Show("User Added Successfully! Please validate the phone number.");
                CodeEntry codeEntry = new CodeEntry(txtUsername.Text, txtPhone.Text);
                codeEntry.ShowDialog();
            }
            else
            {
                MessageBox.Show("Unable to add the user");
            }
        }
        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                CognitoHelper cognitoHelper = new CognitoHelper();
                cognitoUser = await cognitoHelper.ValidateUser(txtusername.Text, txtpassword.Text);

                Console.WriteLine(cognitoUser.Username);
                string bucketsforuser = await cognitoHelper.GetS3BucketsAsync(cognitoUser);

                MessageBox.Show(bucketsforuser, "Buckets for the users");
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp);
                MessageBox.Show("Unable to validate the username and password");
            }
        }
Пример #17
0
        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                CognitoHelper helper = new CognitoHelper();
                await helper.ResetPassword(txtusername.Text);

                MessageBox.Show("Password reset request submitted. Please check the code on phone");
                lblcode.Enabled        = true;
                txtcode.Enabled        = true;
                lblnewpassword.Enabled = true;
                txtnewpassword.Enabled = true;
                btnupdatepass.Enabled  = true;
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }
Пример #18
0
        private async void btnLogIn_Click(object sender, EventArgs e)
        {
            CognitoHelper cognitoHelper = new CognitoHelper();

            try
            {
                var cognitoUser = await cognitoHelper.ValidateUser(txtUsername.Text, txtPassword.Text);

                MessageBox.Show("Validated!");
            }
            catch (Amazon.CognitoIdentityProvider.Model.UserNotFoundException)
            {
                errorUI("User not found");
            }
            catch (Amazon.CognitoIdentityProvider.Model.InvalidPasswordException)
            {
                errorUI("Invalid password");
            }
            catch (Exception)
            {
                errorUI("Unexpected error");
            }
        }
Пример #19
0
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CognitoHelper cognitoHelper = new CognitoHelper();

            System.Diagnostics.Process.Start(cognitoHelper.GetCustomHostedURL());
        }
Пример #20
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);
        }
Пример #21
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 != null && pRequest.Headers.Count > 0 && pRequest.Headers.Keys.Contains("warmup"))
            {
                return(HttpHelper.WarmupResponse());
            }
            var vResponse = HttpHelper.HandleError("[UserRequestsLambda] Unknown Backend error", 500);

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

            try
            {
                using (opendkpContext vDatabase = new opendkpContext())
                {
                    //For these operations, we should have the CognitoInfo user available to us
                    if (pRequest.Headers != null && !pRequest.Headers.ContainsKey("cognitoinfo"))
                    {
                        return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                    }

                    CognitoUser vCognitoUser = CognitoHelper.GetCognitoUser(pRequest.Headers["cognitoinfo"]);
                    if (pRequest.HttpMethod.Equals("GET", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //If the GET request has PathParameter of the account, fetch all requests for given account
                        //Otherwise return all requests
                        if (pRequest != null && pRequest.PathParameters != null && pRequest.PathParameters.Count > 0)
                        {
                            string vAccountName = pRequest.PathParameters["account"];
                            vResponse = GetAccountRequests(vDatabase, vAccountName, vClientId);
                        }
                        else
                        {
                            vResponse = GetAllRequests(vDatabase, vClientId);
                        }
                    }

                    //PUT can come from any user, such as a standard user who wants to assign a character to themselves
                    //or credit for a raid tick.
                    if (pRequest.HttpMethod.Equals("PUT", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (vCognitoUser == null)
                        {
                            return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                        }
                        UserRequests vUserRequest = JsonConvert.DeserializeObject <UserRequests>(pRequest.Body);
                        if (vUserRequest.RequestType == UserRequests.TYPE_CHARACTER_ASSIGN)
                        {
                            vResponse = HandleCharacterAssignRequest(vDatabase, vUserRequest, pRequest, vCognitoUser);
                        }
                        if (vUserRequest.RequestType == UserRequests.TYPE_RAIDTICK)
                        {
                            vResponse = HandleRaidTickRequest(vDatabase, vUserRequest, pRequest, vCognitoUser);
                        }
                    }

                    //POST can only come from admins, need to make sure cognito Groups contains "DKP_ADMIN" or "SITE_ADMIN"
                    //This would be for approving or denying requests
                    if (pRequest.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (!CognitoHelper.IsDkpAdmin(pRequest) ||
                            !CognitoHelper.IsAuthorizedAdmin(vDatabase, pRequest))
                        {
                            return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                        }
                        vCognitoUser = CognitoHelper.GetCognitoUser(pRequest.Headers["cognitoinfo"]);

                        UserRequests vUserRequest = JsonConvert.DeserializeObject <UserRequests>(pRequest.Body);
                        if (vUserRequest.RequestType == UserRequests.TYPE_CHARACTER_ASSIGN)
                        {
                            vResponse = UpdateCharacterAssignRequest(vDatabase, vClientId, vUserRequest, vCognitoUser);
                        }
                        if (vUserRequest.RequestType == UserRequests.TYPE_RAIDTICK)
                        {
                            vResponse = UpdateRaidTickRequest(vDatabase, vUserRequest, vCognitoUser, vClientId);
                        }
                    }
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError("[UserRequestsLambda] Issue with DB or Query: " + vException.Message, 500);
            }

            return(vResponse);
        }