示例#1
0
 public ComponentModel(
     string id,
     IEnumerable<ServiceModel> services,
     string limitTypeId,
     IDictionary<string, string> metadata,
     string targetComponentId,
     OwnershipModel ownership,
     SharingModel sharing,
     LifetimeModel lifetime,
     ActivatorModel activator)
 {
     if (id == null) throw new ArgumentNullException("id");
     if (services == null) throw new ArgumentNullException("services");
     if (limitTypeId == null) throw new ArgumentNullException("limitTypeId");
     if (metadata == null) throw new ArgumentNullException("metadata");
     if (targetComponentId == null) throw new ArgumentNullException("targetComponentId");
     _id = id;
     _limitTypeId = limitTypeId;
     _metadata = new Dictionary<string,string>(metadata);
     _services = services.ToArray();
     _targetComponentId = targetComponentId;
     _ownership = ownership;
     _sharing = sharing;
     _lifetime = lifetime;
     _activator = activator;
 }
        // Replace the contents of a view (invoked by the layout manager)
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            SharingModel item = items[position];

            if (holder is SharingAdapterViewHolder viewHolder)
            {
                viewHolder.NameTextView.Text = item.Name;
            }

            //holder.TextView.Text = items[position];
        }
        public ActionResult FileExport(ClaimSetFileExportModel claimSetFileExportModel)
        {
            var exports             = _claimSetFileExportCommand.Execute(claimSetFileExportModel);
            var currentDate         = DateTime.Now.ToString("MM/dd/yyyy hh:mm tt");
            var exportClaimSetModel = new ExportClaimSetPreviewModel
            {
                DownLoadFileTitle   = $"{exports.Title}({currentDate})",
                ExportPreviewString = SharingModel.SerializeFromSharingModel(exports)
            };

            return(PartialView("_ExportClaimSetPreview", exportClaimSetModel));
        }
示例#4
0
        internal static ISharing Get()
        {
            if (_Sharing != null)
            {
                return(_Sharing);
            }
            var x = new SharingModel(
                );

            _Sharing           = x;
            x.ApplicationState = Kernel_ApplicationState.Get();
            return(_Sharing);
        }
示例#5
0
 public Component(string id, TypeData limitType, IEnumerable<Service> services, OwnershipModel ownership, SharingModel sharing, IDictionary<string, string> metadata, ActivatorModel activator, LifetimeModel lifetime, string targetComponentId = null)
 {
     if (limitType == null) throw new ArgumentNullException("limitType");
     if (services == null) throw new ArgumentNullException("services");
     if (metadata == null) throw new ArgumentNullException("metadata");
     _id = id;
     _limitType = limitType;
     _services = services.ToArray();
     _ownership = ownership;
     _sharing = sharing;
     _metadata = metadata;
     _activator = activator;
     _lifetime = lifetime;
     _targetComponentId = targetComponentId;
 }
            public ClaimSetFileImportModelValidator(ISecurityContext securityContext)
            {
                RuleFor(m => m.ImportFile).NotEmpty();

                When(m => m.ImportFile != null, () =>
                {
                    RuleFor(x => x.ImportFile)
                    .SafeCustom((model, context) =>
                    {
                        var validator    = new SharingModelValidator(securityContext, context.PropertyName);
                        var sharingModel = SharingModel.Deserialize(model);
                        context.AddFailures(validator.Validate(sharingModel));
                    });
                });
            }
示例#7
0
        private static async Task sendData(SharingModel obj)
        {
            try
            {
                JSONObject jsonObj = new JSONObject().Put("from", Utils.GetDefaults("Id")).Put("email", obj.Email);
                Log.Error("DeleteSharing", "sending obj: " + jsonObj);
                if (Utils.CheckNetworkAvailability())
                {
                    string result = await WebServices.WebServices.Post($"{Constants.PublicServerAddress}/api/deleteSharingPeople", jsonObj, Utils.GetDefaults("Token"));

                    Log.Error("DeleteSharing", "response: " + result);
                }
            } catch (Exception e) {
                Log.Error("DeleteSharing err ", e.Message);
            }
        }
示例#8
0
 public ComponentModel(
     string id,
     IEnumerable <ServiceModel> services,
     string limitTypeId,
     IDictionary <string, string> metadata,
     string targetComponentId,
     OwnershipModel ownership,
     SharingModel sharing,
     LifetimeModel lifetime,
     ActivatorModel activator)
 {
     if (id == null)
     {
         throw new ArgumentNullException("id");
     }
     if (services == null)
     {
         throw new ArgumentNullException("services");
     }
     if (limitTypeId == null)
     {
         throw new ArgumentNullException("limitTypeId");
     }
     if (metadata == null)
     {
         throw new ArgumentNullException("metadata");
     }
     if (targetComponentId == null)
     {
         throw new ArgumentNullException("targetComponentId");
     }
     _id                = id;
     _limitTypeId       = limitTypeId;
     _metadata          = new Dictionary <string, string>(metadata);
     _services          = services.ToArray();
     _targetComponentId = targetComponentId;
     _ownership         = ownership;
     _sharing           = sharing;
     _lifetime          = lifetime;
     _activator         = activator;
 }
示例#9
0
        public async Task <HttpResponseMessage> SharePicture(SharingModel sharingModel)
        {
            try
            {
                if (sharingModel == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                var shareEntries = sharingModel.ShareToUsers.Select(toUserId => new ShareEntry(sharingModel.OwnerUserId, toUserId, sharingModel.PictureId, sharingModel.PictureUrl));
                await Repository.SaveShareEntries(shareEntries);

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(new ResponseModel {
                    HasError = true, ErrorMessage = ex.Message
                }));
            }
        }
示例#10
0
 public Component(string id, TypeData limitType, IEnumerable <Service> services, OwnershipModel ownership, SharingModel sharing, IDictionary <string, string> metadata, ActivatorModel activator, LifetimeModel lifetime, string targetComponentId = null)
 {
     if (limitType == null)
     {
         throw new ArgumentNullException("limitType");
     }
     if (services == null)
     {
         throw new ArgumentNullException("services");
     }
     if (metadata == null)
     {
         throw new ArgumentNullException("metadata");
     }
     _id                = id;
     _limitType         = limitType;
     _services          = services.ToArray();
     _ownership         = ownership;
     _sharing           = sharing;
     _metadata          = metadata;
     _activator         = activator;
     _lifetime          = lifetime;
     _targetComponentId = targetComponentId;
 }
示例#11
0
        public void ShouldImportClaimSet()
        {
            var testApplication = new Application
            {
                ApplicationName = $"Test Application {DateTime.Now:O}"
            };

            Save(testApplication);

            SetupResourceClaims(testApplication);

            var testJSON = @"{
                ""title"": ""testfile"",
                ""template"": {
                    ""claimSets"": [
                      {
                        ""name"": ""Test Claimset"",
                        ""resourceClaims"": [
                          {
                            ""Name"": ""TestParentResourceClaim1"",
                            ""Read"": true,
                            ""Create"": false,
                            ""Update"": false,
                            ""Delete"": false,
                            ""Children"": []
                          },
                          {
                            ""Name"": ""TestParentResourceClaim2"",
                            ""Read"": true,
                            ""Create"": false,
                            ""Update"": false,
                            ""Delete"": false,	
                            ""Children"": []
                          },
                          {
                            ""Name"": ""TestParentResourceClaim3"",
                            ""Read"": true,
                            ""Create"": true,
                            ""Update"": true,
                            ""Delete"": true,
                            ""Children"": []
                          }
                        ]
                      }
                    ]
                }
            }";

            var importModel        = GetImportModel(testJSON);
            var importSharingModel = SharingModel.DeserializeToSharingModel(importModel.ImportFile.OpenReadStream());

            Scoped <ClaimSetFileImportCommand>(command => command.Execute(importSharingModel));

            var testClaimSet = Transaction(securityContext => securityContext.ClaimSets.SingleOrDefault(x => x.ClaimSetName == "Test Claimset"));

            testClaimSet.ShouldNotBeNull();

            var resourcesForClaimSet =
                Scoped <IGetResourcesByClaimSetIdQuery, List <Management.ClaimSetEditor.ResourceClaim> >(
                    query => query.AllResources(testClaimSet.ClaimSetId).ToList());

            resourcesForClaimSet.Count.ShouldBeGreaterThan(0);
            var testResources = resourcesForClaimSet.Where(x => x.ParentId == 0).ToArray();

            testResources.Count().ShouldBe(3);

            var testResource1 = testResources[0];

            MatchActions(testResource1, "TestParentResourceClaim1", new bool[] { false, true, false, false });

            var testResource2 = testResources[1];

            MatchActions(testResource2, "TestParentResourceClaim2", new bool[] { false, true, false, false });

            var testResource3 = testResources[2];

            MatchActions(testResource3, "TestParentResourceClaim3", new bool[] { true, true, true, true });
        }
示例#12
0
        public void ShouldImportClaimSetResourceClaimWithChildrenAndAuthrozationStrategyOverrides()
        {
            var testApplication = new Application
            {
                ApplicationName = $"Test Application {DateTime.Now:O}"
            };

            Save(testApplication);

            var appAuthorizationStrategies = SetupApplicationAuthorizationStrategies(testApplication, 3).ToList();

            SetupResourceClaims(testApplication, 1, 1);

            var testJSON          = @"{
                ""title"": ""testfile"",
                ""template"": {
                    ""claimSets"": [
                      {
                        ""name"": ""Test Claimset"",
                        ""resourceClaims"": [
                          {
                            ""Name"": ""TestParentResourceClaim1"",
                            ""Read"": true,
                            ""Create"": true,
                            ""Update"": false,
                            ""Delete"": false,
                            ""AuthStrategyOverridesForCRUD"": [
                                  {
                                    ""AuthStrategyId"": {0},
                                    ""AuthStrategyName"": ""{1}"",
                                    ""DisplayName"": ""{1}"",
                                    ""IsInheritedFromParent"": false
                                  },
                                  {
                                    ""AuthStrategyId"": {2},
                                    ""AuthStrategyName"": ""{3}"",
                                    ""DisplayName"": ""{3}"",
                                    ""IsInheritedFromParent"": false
                                  },
                                  null,
                                  null
                                ],
                             ""Children"": [
                                    {
                                        ""Name"": ""TestChildResourceClaim1"",
                                        ""Read"": true,
                                        ""Create"": true,
                                        ""Update"": true,
                                        ""Delete"": false,
                                        ""AuthStrategyOverridesForCRUD"": [
                                          {
                                            ""AuthStrategyId"": {0},
                                            ""AuthStrategyName"": ""{1}"",
                                            ""DisplayName"": ""{1}"",
                                            ""IsInheritedFromParent"": true
                                          },
                                          {
                                            ""AuthStrategyId"": {2},
                                            ""AuthStrategyName"": ""{3}"",
                                            ""DisplayName"": ""{3}"",
                                            ""IsInheritedFromParent"": true
                                          },
                                          {
                                            ""AuthStrategyId"": {4},
                                            ""AuthStrategyName"": ""{5}"",
                                            ""DisplayName"": ""{5}"",
                                            ""IsInheritedFromParent"": false
                                          },
                                          null
                                        ]
                                    }
                               ]
                          }
                        ]
                      }
                    ]
                }
            }";
            var authStrategy1Id   = appAuthorizationStrategies[0].AuthorizationStrategyId;
            var authStrategy1Name = appAuthorizationStrategies[0].AuthorizationStrategyName.ToString();

            var authStrategy2Id   = appAuthorizationStrategies[1].AuthorizationStrategyId;
            var authStrategy2Name = appAuthorizationStrategies[1].AuthorizationStrategyName.ToString();

            var authStrategy3Id   = appAuthorizationStrategies[2].AuthorizationStrategyId;
            var authStrategy3Name = appAuthorizationStrategies[2].AuthorizationStrategyName.ToString();

            var formattedJson = testJSON.Replace("{0}", authStrategy1Id.ToString())
                                .Replace("{1}", authStrategy1Name)
                                .Replace("{2}", authStrategy2Id.ToString())
                                .Replace("{3}", authStrategy2Name)
                                .Replace("{4}", authStrategy3Id.ToString())
                                .Replace("{5}", authStrategy3Name);

            var importModel        = GetImportModel(formattedJson);
            var importSharingModel = SharingModel.DeserializeToSharingModel(importModel.ImportFile.OpenReadStream());

            Scoped <ClaimSetFileImportCommand>(command => command.Execute(importSharingModel));

            var testClaimSet = Transaction(securityContext => securityContext.ClaimSets.SingleOrDefault(x => x.ClaimSetName == "Test Claimset"));

            testClaimSet.ShouldNotBeNull();

            var resourcesForClaimSet =
                Scoped <IGetResourcesByClaimSetIdQuery, List <ResourceClaim> >(
                    query => query.AllResources(testClaimSet.ClaimSetId).ToList());

            resourcesForClaimSet.Count.ShouldBeGreaterThan(0);
            var testResources = resourcesForClaimSet.Where(x => x.ParentId == 0).ToArray();

            testResources.Count().ShouldBe(1);

            var testResource1 = testResources[0];

            MatchActions(testResource1, "TestParentResourceClaim1", new bool[] { true, true, false, false });

            testResource1.Children.Count.ShouldBe(1);
            var childResource = testResource1.Children[0];

            childResource.ShouldNotBeNull();

            testResource1.AuthStrategyOverridesForCRUD.ShouldNotBeNull();
            testResource1.AuthStrategyOverridesForCRUD.Length.ShouldBe(4);

            var parentAuthStrategyOverrideForCreate = testResource1.AuthStrategyOverridesForCRUD.Create();

            parentAuthStrategyOverrideForCreate.ShouldNotBeNull();
            parentAuthStrategyOverrideForCreate.AuthStrategyId.ShouldBe(authStrategy1Id);
            parentAuthStrategyOverrideForCreate.AuthStrategyName.ShouldBe(authStrategy1Name);

            var parentAuthStrategyOverrideForRead = testResource1.AuthStrategyOverridesForCRUD.Read();

            parentAuthStrategyOverrideForRead.ShouldNotBeNull();
            parentAuthStrategyOverrideForRead.AuthStrategyId.ShouldBe(authStrategy2Id);
            parentAuthStrategyOverrideForRead.AuthStrategyName.ShouldBe(authStrategy2Name);

            var childAuthStrategyOverrideForCreate = childResource.AuthStrategyOverridesForCRUD.Create();

            childAuthStrategyOverrideForCreate.ShouldNotBeNull();
            childAuthStrategyOverrideForCreate.AuthStrategyId.ShouldBe(authStrategy1Id);
            childAuthStrategyOverrideForCreate.AuthStrategyName.ShouldBe(authStrategy1Name);
            childAuthStrategyOverrideForCreate.IsInheritedFromParent.ShouldBeTrue();

            var childAuthStrategyOverrideForRead = childResource.AuthStrategyOverridesForCRUD.Read();

            childAuthStrategyOverrideForRead.ShouldNotBeNull();
            childAuthStrategyOverrideForRead.AuthStrategyId.ShouldBe(authStrategy2Id);
            childAuthStrategyOverrideForRead.AuthStrategyName.ShouldBe(authStrategy2Name);
            childAuthStrategyOverrideForRead.IsInheritedFromParent.ShouldBeTrue();

            var childAuthStrategyOverrideForUpdate = childResource.AuthStrategyOverridesForCRUD.Update();

            childAuthStrategyOverrideForUpdate.ShouldNotBeNull();
            childAuthStrategyOverrideForUpdate.AuthStrategyId.ShouldBe(authStrategy3Id);
            childAuthStrategyOverrideForUpdate.AuthStrategyName.ShouldBe(authStrategy3Name);
            childAuthStrategyOverrideForUpdate.IsInheritedFromParent.ShouldBeFalse();
        }
示例#13
0
 public SharingModel AsSharingModel()
 {
     return(_sharingModel ??= SharingModel.DeserializeToSharingModel(ImportFile.OpenReadStream()));
 }
示例#14
0
        private async void LoadData(View view)
        {
            try
            {
                var progressBarDialog = new ProgressBarDialog("Asteptati", "Se incarca datele...", Activity, false);
                progressBarDialog.Show();
                // Initialize contacts
                List <SharingModel> contacts = null;
                await Task.Run(async() =>
                {
                    string response = await WebServices.WebServices.Post($"{Constants.PublicServerAddress}/api/getSharedPeople",
                                                                         new JSONObject().Put("id", Utils.GetDefaults("Id")),
                                                                         Utils.GetDefaults("Token"));
                    if (!string.IsNullOrEmpty(response))
                    {
                        contacts = JsonConvert.DeserializeObject <List <SharingModel> >(response);
                        Log.Error("ListaConexiuni", "No. of contacts: " + contacts.Count);
                    }
                });


                Activity.RunOnUiThread(() =>
                {
                    progressBarDialog.Dismiss();
                });



                if (contacts != null)
                {
                    var adapter = new SharingAdapter(contacts);
                    _sharingRecyclerView.SetAdapter(adapter);
                    _sharingRecyclerView.SetLayoutManager(new LinearLayoutManager(Activity));
                    adapter.ItemClick += delegate(object sender, SharingAdapterClickEventArgs args)
                    {
                        string name  = contacts[args.Position].Name;
                        string email = contacts[args.Position].Email;
                        CustomDialogProfileSharingData dialog = OpenMiniProfileDialog();
                        dialog.Name.Text = name;
                        Glide.With(this).Load($"{Constants.PublicServerAddress}/{contacts[args.Position].Avatar}").Into(dialog.Image);

                        dialog.ButtonConfirm.Visibility = ViewStates.Gone;
                        dialog.ButtonCancel.Text        = "Sterge";
                        dialog.ButtonCancel.SetPadding(5, 5, 5, 5);
                        dialog.ButtonCancel.Click += delegate {
                            AlertDialog alertDialog = new AlertDialog.Builder(Activity, Resource.Style.AppTheme_Dialog).Create();
                            alertDialog.SetTitle("Avertisment");
                            alertDialog.SetMessage("Doriti sa stergeti aceasta conexiune?");
                            alertDialog.SetButton("Da", async delegate
                            {
                                SharingModel obj = adapter.getItemAt(args.Position);

                                adapter.DeleteItemAt(args.Position);
                                adapter.NotifyDataSetChanged();

                                //item deleted from list, call server
                                await sendData(obj);

                                dialog.Dismiss();
                                //                                var serialized = JsonConvert.SerializeObject(contacts);
                                //                                Utils.SetDefaults("Rooms", serialized, Activity);
                            });
                            alertDialog.SetButton2("Nu", delegate { });
                            alertDialog.Show();
                        };
                    };
                    adapter.ItemLongClick += delegate(object sender, SharingAdapterClickEventArgs args)
                    {
                        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                        {
                            AlertDialog alertDialog = new AlertDialog.Builder(Activity, Resource.Style.AppTheme_Dialog).Create();
                            alertDialog.SetTitle("Avertisment");
                            alertDialog.SetMessage("Doriti sa stergeti aceasta conexiune?");
                            alertDialog.SetButton("Da", delegate
                            {
                                adapter.DeleteItemAt(args.Position);
                                adapter.NotifyDataSetChanged();
                                //                                var serialized = JsonConvert.SerializeObject(contacts);
                                //                                Utils.SetDefaults("Rooms", serialized, Activity);
                            });
                            alertDialog.SetButton2("Nu", delegate { });
                            alertDialog.Show();
                        }
                        else
                        {
                            AlertDialog alertDialog = new AlertDialog.Builder(Activity, Resource.Style.AppTheme_Dialog).Create();
                            alertDialog.SetTitle("Avertisment");
                            alertDialog.SetMessage("Doriti sa stergeti aceasta conexiune?");
                            alertDialog.SetButton("Da", delegate
                            {
                                adapter.DeleteItemAt(args.Position);
                                adapter.NotifyDataSetChanged();
                                //                                var serialized = JsonConvert.SerializeObject(contacts);
                                //                                Utils.SetDefaults("Rooms", serialized, Activity);
                            });
                            alertDialog.SetButton2("Nu", delegate
                            {
                                //just close dialog
                            });
                            alertDialog.Show();
                        }
                    };
                }
            }
            catch (Exception e)
            {
                e.PrintStackTrace();
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            /*
             * var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
             *
             * ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
             *
             * if (user == null)
             * {
             *  context.SetError("invalid_grant", "The user name or password is incorrect.");
             *  return;
             * }
             *
             * */

            PrivateEncryption privateEncrytion = new PrivateEncryption(ConfigHelper.GetPasswordCryptoSecretKey());
            string            strUserName      = context.UserName;
            string            strPassword      = context.Password;

            if (context.Scope[0].ToLower() == "autologin")
            {
                string decryptedPODetails = privateEncrytion.Decrypt(context.Password.Replace("~", "/").Replace("`", "="));

                string[] strAuthDetails   = decryptedPODetails.Split(new string[] { "POKeyValue" }, StringSplitOptions.None);
                string   strLoginUserName = strAuthDetails[0].ToString();
                string   strKeyValue      = strAuthDetails[1].ToString();

                string decryptTimeStamp = strKeyValue;
                bool   expired          = Math.Abs((DateTime.UtcNow - new DateTime(Convert.ToInt64(decryptTimeStamp))).TotalMinutes) < intTokenValidTime;

                if (!expired)
                {
                    context.SetError("invalid_grant", "Token expired. Please try again.");
                    return;
                }

                strUserName = strPassword = strAuthDetails[0].ToString();
            }
            int? userId           = null;
            int? districtId       = null;
            bool isFirstTimeLogin = false;
            //string password = context.Password.Substring(0, Math.Min(context.Password.Length, 12));
            string encyptedPassword = context.Scope[0].ToLower() == "supportlogin" ? strPassword : privateEncrytion.Encrypt(strPassword);
            byte?  isValid          = UserSecurity.AuthenticateUser(strUserName, encyptedPassword, ref userId, ref districtId);

            if (userId == 0)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            DataTable    dtsocialShare = null;
            SharingModel SocialShare   = new SharingModel();

            if (districtId != null)
            {
                dtsocialShare = UserSecurity.GetsocialShare(districtId.Value);

                foreach (DataRow drShare in dtsocialShare.Rows)
                {
                    SocialShare.FaceBookSharing  = drShare.Field <bool>("Facebook Share");
                    SocialShare.InstagramSharing = drShare.Field <bool>("Instagram Share");
                    SocialShare.TwitterSharing   = drShare.Field <bool>("Twitter Share");
                }
            }

            UserProfile ud  = UserSecurity.RetrieveUserDetail(userId);
            District    isd = District.GetDistrict(districtId);

            if (ud.LastLoginDate == Convert.ToDateTime("1/1/1900 12:00:00 AM") || ud.LastLoginDate == DateTime.MinValue || ud.LastLoginDate == null)
            {
                isFirstTimeLogin = true;
            }
            else
            {
                isFirstTimeLogin = false;
            }

            switch (isValid)
            {
            case 0:     //User successfully logged in
                /*
                 * if (UrlHelper.CanUserLoginToRequestedURL(districtId))
                 * {
                 *  Security.Login(userId);
                 *  PageHelper.TransferUserToDefaultPage();
                 * }
                 * else
                 * {
                 *  PrivateEncryption encryption = new PrivateEncryption(ConfigHelper.GetPasswordCryptoSecretKey());
                 *  PageHelper.TransferToPage(UrlHelper.GetOperationUrl("LOGIN", districtId) + "?cd="
                 + Server.UrlEncode(encryption.Encrypt(string.Format(DateTime.Now + "|" + userNameTextBox.Text + "|" + encryption.Encrypt(userPasswordTextBox.Text.Trim())))));
                 + }
                 */
                UserSecurity.UpdateLastLoginDate(userId, DateTime.Now);
                //Cannot use Activity Logging because it relys on Session.
                //ActivityLogging.AddActivity(ActivityKey.Login);
                //ActivityLogging.UpdateActivity(true, "");
                break;

            case 1:
                //User does not exist
                context.SetError("invalid_grant", MessagesList.ERR_LOGIN_NOTREGISTER);
                return;

            case 2:
                //Password failed
                context.SetError("invalid_grant", MessagesList.ERR_LOGIN_PASSWORDFAILED);
                return;

            case 3:
                //Failed login attempts exceeded
                string error = string.Format(MessagesList.ERR_LOGIN_PASSWORDFAILEDATTEMPTSMORE, Setting.GetSettingValue(SettingMasterKey.AllowableFailedLoginAttempts, districtId), Setting.GetSettingValue(SettingMasterKey.AllowableReLoginDurationAfterexceedingTheAllowableFailedLoginAttempts, districtId));
                context.SetError("invalid_grant", error);
                return;

            case 4:
                //User disabled
                context.SetError("invalid_grant", MessagesList.ERR_LOGIN_PASSWORDDISABLED);
                return;

            case 5:
                //User registered but not activated
                context.SetError("invalid_grant", MessagesList.ERR_LOGIN_REGISTERNOTACTIVATED);
                return;
            }

            double?studentBalance = null;

            studentBalance = Student.GetStudentBalance((int)userId);
            //if (!ud.IsParent)
            //{
            //    context.SetError("invalid_grant", "Only parents are allowed to login");
            //    return;
            //}

            ClaimsIdentity oAuthIdentity   = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            if (ud.AccessId == 3 || ud.AccessId == 4)
            {
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
            }
            else
            {
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "User"));
            }

            Claim claim = new Claim("UserId", userId.ToString());

            oAuthIdentity.AddClaim(claim);
            cookiesIdentity.AddClaim(claim);

            if (districtId == null)
            {
                districtId = 0;
            }
            claim = new Claim("DistrictId", districtId.ToString());
            oAuthIdentity.AddClaim(claim);
            cookiesIdentity.AddClaim(claim);

            if (isd != null)
            {
                claim = new Claim("DistrictName", isd.DistrictName);
                oAuthIdentity.AddClaim(claim);
                cookiesIdentity.AddClaim(claim);
            }

            claim = new Claim("UserName", strUserName);
            oAuthIdentity.AddClaim(claim);
            cookiesIdentity.AddClaim(claim);

            claim = new Claim("AccessLevel", ud.AccessId.ToString());
            oAuthIdentity.AddClaim(claim);
            cookiesIdentity.AddClaim(claim);

            string cd          = privateEncrytion.Encrypt(DateTime.Now.ToString() + "|" + strUserName + "|" + encyptedPassword);
            string redirectURL = Setting.GetDefaultValue(22);
            string APPEB       = Setting.GetSettingValue(SettingMasterKey.EligibilityBenefitsForAPP, districtId.Value);
            string WEBAB       = Setting.GetSettingValue(SettingMasterKey.EligibilityBenefitsForWEB, districtId.Value);
            string showPic     = Setting.GetSettingValue(SettingMasterKey.ShowPicturesFromPrimeroEdge, districtId.Value);
            long   TimeStamp   = DateTime.UtcNow.Ticks;

            //Upon login, display a message to confirm email address for users that have not logged in recently i.e 90Days.
            double LoginDiffDays  = 0;
            bool   LoginDiffrence = false;

            if (context.Scope[0].ToLower() != "autologin")
            {
                if (ud.LastLoginDate.Value.ToShortDateString() == "1/1/1900")
                {
                    LoginDiffrence = false;
                }
                else
                {
                    LoginDiffDays = (DateTime.Now - ud.LastLoginDate.Value).TotalDays;
                }

                if (LoginDiffDays >= 90)
                {
                    LoginDiffrence = true;
                }
            }

            string encyptedTimeStamp = privateEncrytion.Encrypt(TimeStamp.ToString());

            AuthenticationProperties properties = CreateProperties(strUserName);

            properties.Dictionary.Add("FirstName", ud.ContactInformation.FirstName);
            properties.Dictionary.Add("DistrictName", isd == null ? "" : isd.DistrictName);
            properties.Dictionary.Add("Status", isd == null ? "" : isd.Status.ToString());
            properties.Dictionary.Add("AccessLevel", ud.AccessId.ToString());
            properties.Dictionary.Add("RedirectURL", redirectURL);
            properties.Dictionary.Add("StudentBalance", studentBalance.ToString());
            properties.Dictionary.Add("FaceBookSharing", SocialShare.FaceBookSharing.ToString());
            properties.Dictionary.Add("InstagramSharing", SocialShare.InstagramSharing.ToString());
            properties.Dictionary.Add("TwitterSharing", SocialShare.TwitterSharing.ToString());
            properties.Dictionary.Add("ISDId", districtId.ToString());
            properties.Dictionary.Add("APPEB", APPEB);
            properties.Dictionary.Add("WEBEB", WEBAB);
            properties.Dictionary.Add("OnlineAppsToken", encyptedTimeStamp);
            properties.Dictionary.Add("UserId", userId.ToString());
            properties.Dictionary.Add("LoginDiffrence", LoginDiffrence.ToString());
            properties.Dictionary.Add("Email", ud.ContactInformation.Email);
            properties.Dictionary.Add("Verified", ud.Verified?.ToString());
            properties.Dictionary.Add("ShowPicture", showPic);
            properties.Dictionary.Add("IsFirstTimeLogin", Convert.ToString(isFirstTimeLogin));
            properties.Dictionary.Add("UserIP", Helper.GetIP());
            properties.Dictionary.Add("UserTypeId", Convert.ToString(ud.UserTypeId));

            if (districtId != 0)
            {
                properties.Dictionary.Add("OnlineAppURL", Helper.GetOnlineAppUrl(districtId.Value));
            }

            //properties.Dictionary.Add("SocialShare", (new JavaScriptSerializer().Serialize(SocialShare)).Replace("\"", ""));
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }