protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DataTable dt = new DataTable();
            if (HttpContext.Current.Application["Administrator"].ToString().Contains(UserSession.Current.UserAccount.ToLower()))
            {
                dt = UserPermission.GetModulesByLevel(ModuleLevel.All);
            }
            else
            {
                dt = new UserPermission(UserSession.Current.UserAccount).GetModulesByLevelWithRight(ModuleLevel.All);
            }

            InitTree(this.MenuTreeView.Nodes, "0",dt); //递归生成树。

            if (Session["NodeIndex"] != null)
            {
                int index = Convert.ToInt32(Session["NodeIndex"]);
                this.MenuTreeView.Nodes[index].Expanded = true;
            }
            else
            {
                this.MenuTreeView.Nodes[0].Expanded = true;
            }
        }
    }
 public void CreateUserPermissions(User user, IList<Permission> rList)
 {
     foreach (Permission permission in rList)
     {
         UserPermission userPermission = new UserPermission();
         userPermission.User = user;
         userPermission.Permission = permission;
         entityDao.CreateUserPermission(userPermission);
     }
 }
Beispiel #3
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                MembershipCreateStatus status;
                Membership.CreateUser(txtUserName.Text.Trim(), txtPassWord.Text, txtEmail.Text, null, null, true, out status);
                if (status.ToString() == "Success")
                {
                    UserPermission userpr = new UserPermission();
                    userpr.Username = txtUserName.Text;
                    userpr.CompanyId = int.Parse(cboCompanyName.SelectedValue);
                    userpr.AppPermission = chkAppPermission.Checked;
                    if (cboPermission.SelectedValue == "")
                        userpr.WebPermission = null;
                    else
                        userpr.WebPermission = cboPermission.SelectedValue;

                    userpr.CreateAccount = this.User.Identity.Name;
                    userpr.Insert();

                    //Send email created user
                    string mailBodyTemplate = Server.MapPath("~/Template/" + Common.AppSettingKey(Constant.MAIL_REGISTER_BODY));

                    List<ParamMailContent> listParameter = new List<ParamMailContent>();
                    string urlPotal = Common.AppSettingKey(Constant.PORTAL_CONFIG);

                    listParameter.Add(new ParamMailContent("{ACCOUNT_ID}", userpr.Username));
                    listParameter.Add(new ParamMailContent("{ACCOUNT_EMAIL}", txtEmail.Text));
                    listParameter.Add(new ParamMailContent("{ACCOUNT_PASS}", txtPassWord.Text));
                    listParameter.Add(new ParamMailContent("{WORKNC_URL}", urlPotal.Replace("Portal" , "")));

                    MailInfo.SendMail(txtEmail.Text ,  Common.AppSettingKey(Constant.MAIL_REGISTER_SUBJECT), mailBodyTemplate,  listParameter);

                    //Reset data
                    txtUserName.Text = txtEmail.Text = string.Empty;
                    cboPermission.SelectedIndex = 0;

                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert(\"" + (GetResource("RegisterUserSuccess") + "\");"), true);

                }
                if (Membership.GetUser(txtUserName.Text).UserName != string.Empty)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert(\"" + GetJSMessage(GetResource("Title_Error"), GetResource("RegisterUserFail")) + "\");", true);
                }
            }
            catch (Exception ex)
            {
                btnRegister.Enabled = true;
                this.btnRegister.Attributes.Add("onclick", "javascript:if (Page_ClientValidate()){ this.disabled=true;}" + Page.ClientScript.GetPostBackEventReference(btnRegister, "").ToString());

                logger.Error("Error Register", ex);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert(\"" + GetJSMessage(GetResource("Title_Error"), ex.Message) + "\");", true);
            }
        }
Beispiel #4
0
 /// <summary>
 /// Determines if the given user has (can use) the provided permission.
 /// </summary>
 /// <param name="user">The user to test against.</param>
 /// <param name="permission">The permission to test for access to.</param>
 /// <returns></returns>
 public static bool HasPermission(User user, UserPermission permission)
 {
     switch (permission)
     {
         case UserPermission.UpVote:
             return user.Reputation >= Settings.Permissions.UpVote;
         case UserPermission.DownVote:
             return user.Reputation >= Settings.Permissions.DownVote;
         case UserPermission.Flag:
             return user.Reputation >= Settings.Permissions.Flag;
         case UserPermission.Edit:
             return user.Reputation >= Settings.Permissions.Edit;
     }
     return false;
 }
 public void CreateCustomer(Customer entity,User currentUser)
 {
     if (partyDao.LoadParty(entity.Code) == null)
     {
         base.CreateCustomer(entity);
     }
     else
     {
         CreateCustomerOnly(entity);
     }
     Permission permission = new Permission();
     permission.Category = permissionCategoryMgrE.LoadPermissionCategory(BusinessConstants.CODE_MASTER_PERMISSION_CATEGORY_TYPE_VALUE_CUSTOMER);
     permission.Code = entity.Code;
     permission.Description = entity.Name;
     permissionMgrE.CreatePermission(permission);
     UserPermission userPermission = new UserPermission();
     userPermission.Permission = permission;
     userPermission.User = currentUser;
     userPermissionMgrE.CreateUserPermission(userPermission);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //string test = "userid=14&permissionId=1";
            //test = Tools.Encrypt(test, true);
            //test = Tools.EncodeTo64(test);

            string code64Encoded = Request.QueryString["code"];
            up = GetUserPermissionDataFromQueryString(code64Encoded);
            if (up != null)
            {
                // call the method to show user First Name
                PostAroundServiceClient client = new PostAroundServiceClient();
                User user = client.GetUserByID(up.userId);
                client.Close();
                ltrlFname.Text = user.firstName;
                if (!IsPostBack)
                {
                    if (UserIsGrantPermission((int)Enums.Permissions.EmailPermission))
                    {
                        bool isSucceed = Unsubscribe();
                        if (isSucceed)
                            ltrlStatus.Text = "You have been unsubscribed!";
                        else
                            ltrlStatus.Text = "Unsubscribtion Failed. Please Try Again.";
                    }
                    else
                        ltrlStatus.Text = "User already unsubscribed.";
                }
            }

        }
        catch (Exception ex)
        {
            PrintStatus(ex.Message);
        }
    }
Beispiel #7
0
        private void updateUserBTN_Click(object sender, EventArgs e)
        {
            if (addingUser)
            {
                string         perm = permissionDD.Text;
                UserPermission up   = userPermissions[perm];
                User           u    = new User(0, loginTB.Text, nameFirstTB.Text, nameLastTB.Text, up.DatabaseID);
                string         pw   = newPassTB.Text;
                string         pwv  = newPassVerifyTB.Text;
                if (pw != pwv)
                {
                    MessageBox.Show("Passwords do not match. Verify they match and try again.");
                }
                else if (!ValidatePassword(pw))
                {
                    MessageBox.Show("Password does not meet the strength requirements. Please update.");
                }
                else
                {
                    if (MessageBox.Show("Adding new user to the database." + Environment.NewLine +
                                        "Name: " + u.FullName() + Environment.NewLine +
                                        "Login: "******"Permission: " + up.Title, "ADDING USER", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
                        == System.Windows.Forms.DialogResult.Yes)
                    {
                        // Add user to database
                        string pwh = FSManager.HashString(pw);
                        db.NewAccount(u, pwh);

                        // Refresh user list
                        EstablishUserManagement();
                    }
                }
            }
            else
            {
                // Editing user
                bool updatePassword = false;

                // Check to see if updating password
                string newPass  = newPassTB.Text;
                string newPassV = newPassVerifyTB.Text;
                if (newPass == newPassV && ValidatePassword(newPass))
                {
                    updatePassword = true;
                }

                if (users.ContainsKey(selUser))
                {
                    User u = users[selUser];
                    users[selUser].NameFirst = nameFirstTB.Text;
                    users[selUser].NameLast  = nameLastTB.Text;
                    users[selUser].Login     = loginTB.Text;
                    string permTitle = permissionDD.Text;
                    if (userPermissions.ContainsKey(permTitle))
                    {
                        UserPermission up = userPermissions[permTitle];
                        users[selUser].PermissionID    = up.DatabaseID;
                        users[selUser].PermissionLevel = up.Level;
                        users[selUser].PermissionTitle = up.Title;
                    }

                    if (updatePassword)
                    {
                        // Do full update
                        db.EditAccount(users[selUser], FSManager.HashString(newPass));
                        EstablishUserManagement();
                    }
                    else
                    {
                        db.EditAccount(users[selUser]);
                        EstablishUserManagement();
                        // Do standard update
                        //db.EditAccount(users[selUser]);
                        //EstablishUserManagement();
                    }
                }
            }
        }
Beispiel #8
0
        public void DeleteUserPermission(UserPermission permmission)
        {
            try
            {

                AuditTrail trail = new AuditTrail();

                trail.TimeStamp = CurrentDate;
                trail.UserId = PersonalInformation.UserId;
                trail.UserIP = _UtilityService.RemoteIP;
                var personIn = EngineContext.Current.Resolve<IUserService>();
                var pp = personIn.GetUserPersonalInformation("", permmission.UserId);
                trail.AuditActionId = (int)Telehire.Core.Utility.SystemEnums.AuditActionEnum.Delete_UserPermission;
                trail.Details = PersonalInformation.FullName + " removed a Permission: " + permmission.Permission.Name + " for user: " + pp.FullName;
                //trail.AirlineId = PersonalInformation.AirlineId;
                _AuditTrailRep.SaveOrUpdate(trail);
            }
            catch
            {

            }
        }
 /// <summary>
 /// The first action check when form load
 /// - Validate only allow IT Members + System Account
 /// </summary>
 protected void FirstLoad()
 {
     // Check and only allow IT Members + Contributors + System Account// System admin
     if (UserPermission.IsCurrentUserInGroup(StringConstant.ITMembers) || UserPermission.IsCurrentUserInGroup(StringConstant.ITContributors) || UserPermission.IsCurrentUserInGroup(StringConstant.SystemAdmin) || (SPContext.Current.Web.CurrentUser.ID == SPContext.Current.Site.SystemAccount.ID))
     {
         // Load and update data to layout
         var model = LoadData();
         UpdateDataToLayout(model);
     }
     else
     {
         // Not allow access page => return to Overview
         Response.Redirect(SPContext.Current.Web.Url + StringConstant.PageOverviewURL);
     }
 }
Beispiel #10
0
 partial void InsertUserPermission(UserPermission instance);
Beispiel #11
0
 partial void UpdateUserPermission(UserPermission instance);
 public void Delete(UserPermission entity)
 {
     _userPermissionStorageApplication.Delete(entity);
 }
    private UserPermission GetUserPermissionDataFromQueryString(string querystring)
    {
        UserPermission up = null;

        if (!string.IsNullOrWhiteSpace(querystring))
        {
            up = new UserPermission();
            string codeEncoded = Tools.DecodeFrom64(querystring);
            string code = Tools.Decrypt(codeEncoded, true);
            // now we got userid=12&permissionId=1
            string userPart = code.Split('&')[0];
            string permissionPart = code.Split('&')[1];
            string strUserId = userPart.Split('=')[1];
            string strPermissionId = permissionPart.Split('=')[1];

            int userId;
            int permissionId;
            Int32.TryParse(strUserId, out userId);
            Int32.TryParse(strPermissionId, out permissionId);

            up.userId = userId;
            up.permissionId = permissionId;
        }

        return up;
    }
        public HttpResponseMessage SaveUserPermission(UserPermission submitted)
        {
            try
            {
                if (!Common.HasGroupWritePermission(submitted.permission.ResourceGroupId))
                    return Request.CreateResponse(HttpStatusCode.Unauthorized, new { Message = App_GlobalResources.Errors.ErrorNotAuthorized });

                var user = Common.GetUser(submitted.userName);

                if (user == null)
                    return Request.CreateResponse(HttpStatusCode.OK, new { Success = false, Message = App_GlobalResources.Errors.ErrorUserNotFound });

                var userPermissions = _repository.GetUserPermissions(submitted.permission.ResourceGroupId, user.UserID);

                if (userPermissions != null && userPermissions.Any())
                    return Request.CreateResponse(HttpStatusCode.OK, new { Success = false, Message = App_GlobalResources.Errors.ErrorUserAlreadyhasPermission });

                var permission = new Permission
                {
                    ResourceGroupId = submitted.permission.ResourceGroupId,
                    UserId = user.UserID,
                    ReadPermission = submitted.permission.ReadPermission,
                    WritePermission = submitted.permission.WritePermission
                };

                return Request.CreateResponse(HttpStatusCode.OK, new { Success = _repository.Create(permission) });
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, App_GlobalResources.Errors.ErrorGeneric);
            }
        }
        private void btnCopy_Click(object sender, EventArgs e)
        {
            UserPermission userPermission = new UserPermission();
            // 读取角色数据
            List<BaseRoleEntity> roleEntites = new List<BaseRoleEntity>();
            for (int i = 0; i < this.cklstRole.CheckedItems.Count; i++)
            {
                BaseRoleEntity roleEntity = new BaseRoleEntity(((System.Data.DataRowView)this.cklstRole.CheckedItems[i]).Row);
                roleEntites.Add(roleEntity);
            }
            // 角色复制到剪切板
            userPermission.RoleEntites = roleEntites;
            // 模块访问权限复制到剪切板
            string[] grantModuleIds = this.GetGrantModuleIds();
            userPermission.GrantModuleIds = grantModuleIds;
            // 操作权限复制到剪切板
            string[] grantPermissionIds = this.GetGrantPermissionIds();
            userPermission.GrantPermissionIds = grantPermissionIds;

            Clipboard.SetData("userPermission", userPermission);
            this.btnPaste.Enabled = true;
        }
Beispiel #16
0
 public virtual void InitializeFromOutput(TOutput output)
 {
     ErrorCode  = ErrorCode.FromString(output.ErrorCode);
     Permission = UserPermission.FromString(output.Permission);
 }
Beispiel #17
0
 partial void DeleteUserPermission(UserPermission instance);
Beispiel #18
0
 public virtual void DeleteUserPermission(UserPermission entity)
 {
     entityDao.DeleteUserPermission(entity);
 }
Beispiel #19
0
 public virtual void UpdateUserPermission(UserPermission entity)
 {
     entityDao.UpdateUserPermission(entity);
 }
Beispiel #20
0
 public virtual void CreateUserPermission(UserPermission entity)
 {
     entityDao.CreateUserPermission(entity);
 }
 public virtual void UpdateUserPermission(UserPermission entity)
 {
     Update(entity);
 }
Beispiel #22
0
 public RequiresPermissionLevel(UserPermission permission)
 {
     Permission = permission;
 }
Beispiel #23
0
			public bool HasPermission(string userName, UserPermission permission)
			{
				if (Users != null)
				{
					userName = userName.ToLower();
					foreach (User user in Users)
					{
						if (userName == user.UserName.ToLower())
						{
							switch (permission)
							{
								case UserPermission.Pages:
									return user.Pages;

								case UserPermission.Images:
									return user.Images;

								case UserPermission.Downloads:
									return user.Downloads;

								default:
									return false;
							}
						}
					}
				}
				return false;
			}
Beispiel #24
0
 /// <summary>
 /// Clear all session and redirect home page
 /// </summary>
 protected void OnLogout()
 {
     UserPermission.SetEmployeeInfo(null);
     Response.Redirect(StringConstant.PageLoginURL);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DataTable dt = new DataTable();
            if (HttpContext.Current.Application["Administrator"].ToString().Contains(UserSession.Current.UserAccount.ToLower()))
            {
                dt = UserPermission.GetModulesByLevel(ModuleLevel.All);
            }
            else
            {
                if (String.IsNullOrEmpty(UserSession.Current.UserAccount))
                {
                    Response.Redirect("~/Login.aspx");
                    return;
                }

                string strLoginType = ConfigurationManager.AppSettings["LoginType"].ToString();
                if ("1".Equals(strLoginType))
                {
                    dt = new UserPermission(UserSession.Current.UserAccount).GetModulesByADWithRight(ModuleLevel.All);
                }
                else
                {
                    dt = new UserPermission(UserSession.Current.UserAccount).GetModulesByLevelWithRight(ModuleLevel.All);
                }
            }

            BasePage.dtUserPage = dt;
            InitTree("0", dt); //递归生成树。

            //if (Session["NodeIndex"] != null)
            //{
            //    int index = Convert.ToInt32(Session["NodeIndex"]);
            //    this.MenuTreeView.Nodes[index].Expanded = true;
            //}
            //else
            //{
            //    this.MenuTreeView.Nodes[0].Expanded = true;
            //}

            //this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "key", "SetMenuList(" + "2" + ")", true);

            SiteMapPath1.NodeStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#3B5998");
            SiteMapPath1.PathSeparatorStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#666666");
        }

        if (!String.IsNullOrEmpty(Request.QueryString["menu"]) && chkParm(Request.QueryString["menu"].ToString()))
        {
           hidMenuSpan.Value = Request.QueryString["menu"].ToString();
        }
        else
        {
            hidMenuSpan.Value = "-1";
        }

        if (!String.IsNullOrEmpty(hidChangeMenu.Value))
        {
            if (Request.RawUrl.Contains("hidmenu"))
            {
                Context.RewritePath(Request.RawUrl.Substring(0, Request.RawUrl.IndexOf("hidmenu")) + "hidmenu=" + hidChangeMenu.Value + Request.RawUrl.Substring(Request.RawUrl.IndexOf("hidmenu") + 9));
                //Request.RawUrl = Request.RawUrl.Substring(0, Request.RawUrl.IndexOf("hidmenu")) + "hidmenu=" + hidChangeMenu.Value + Request.RawUrl.Substring(Request.RawUrl.IndexOf("hidmenu") + 9);
            }
            else
            {
                Context.RewritePath((Request.RawUrl.Contains("?")) ? Request.RawUrl + "&hidmenu=" + hidChangeMenu.Value : Request.RawUrl + "?hidmenu=" + hidChangeMenu.Value);
                //Request.RawUrl = (Request.RawUrl.Contains("?")) ? Request.RawUrl + "&hidmenu=" + hidChangeMenu.Value : Request.RawUrl + "?hidmenu=" + hidChangeMenu.Value;
            }
        }
        //else
        //{
        //    if (Request.RawUrl.Contains("hidmenu"))
        //    {
        //        Context.RewritePath(Request.RawUrl);
        //    }
        //}

        if (Request.Url.ToString().Contains("hidmenu"))
        {
            hidChangeMenu.Value = Request.Url.ToString().Substring(Request.Url.ToString().IndexOf("hidmenu") + 8, 1);
        }

        //this.Page.ClientScript.RegisterOnSubmitStatement(this.Page.GetType(), "btnLoad", "BtnLoadStyle()");
        //this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "btnLoad", "BtnCompleteStyle()");
    }
Beispiel #26
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRole requirement)
        {
            var data = _RoleManngeRepository.GetAll(u => u.Id != null && u.IsTrueRold == requirement.Istrue);
            var list = await(from item in data
                             orderby item.Id
                             select new UserPermission
            {
                Policy    = item.RoleName,
                Id        = item.Id,
                IsEnabled = item.IsTrueRold
            }).ToListAsync();

            requirement.UserPermissions = list;
            var filterContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext);
            var httpContext   = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)?.HttpContext;

            if (httpContext == null)
            {
                httpContext = _Accessor.HttpContext;
            }
            if (httpContext != null)
            {
                var questUrl = httpContext.Request.Path.Value.ToLower();
                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        context.Fail();
                        return;
                    }
                }
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;
                        var currentUserRoles = (from item in httpContext.User.Claims
                                                where item.Type == "jti" || item.Type == requirement.ClaimType
                                                select item.Value.ToString()).ToList();
                        if (currentUserRoles.Count < 2)
                        {
                            httpContext.Response.Redirect(requirement.DeniedAction);
                            return;
                        }
                        var userPermission = new UserPermission();
                        foreach (var role in currentUserRoles)
                        {
                            if (string.IsNullOrEmpty(userPermission.Policy))
                            {
                                var permission = list.Where(x => ((x.Id.ToString().Equals(role)))).FirstOrDefault();

                                if (permission != null)
                                {
                                    userPermission = permission;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (string.IsNullOrEmpty(userPermission.Policy))
                        {
                            context.Fail();
                            return;
                        }
                        context.Succeed(requirement);
                        return;
                    }
                    else
                    {
                        context.Fail();
                        return;
                    }
                }
                else
                {
                    //是登录的api请求
                    //if (!questUrl.Equals(requirement.LoginPath.ToLower()))
                    //{

                    //    context.Succeed(requirement);
                    //    return;
                    //}
                    context.Fail();
                }
            }
            return;
        }
Beispiel #27
0
        public async Task <ActionResult <CommonResponse> > DeleteUserPermission([FromRoute][Username] string username, [FromRoute] UserPermission permission)
        {
            try
            {
                var id = await _userService.GetUserIdByUsernameAsync(username);

                await _userPermissionService.RemovePermissionFromUserAsync(id, permission);

                return(OkWithCommonResponse());
            }
            catch (InvalidOperationOnRootUserException)
            {
                return(BadRequestWithCommonResponse(ErrorCodes.UserController.InvalidOperationOnRootUser, Resource.MessageInvalidOperationOnRootUser));
            }
        }
Beispiel #28
0
        public bool GrantPermission(User user, StandardPermissionAttributes permissionAttribute, string attributeValue, bool removeOnly, User administrator)
        {
            //to apply permissions we add or remove from the permissions list attached to the user details, we also maintain a string in the legacy semicolon seperated format for apps/code which still requires the older format.
            var userDetails = dataModel.Users.FirstOrDefault(u => u.ID == user.ID);

            if (userDetails != null)
            {
                UserPermissionsContainer userPermissions = new UserPermissionsContainer();
                if (!String.IsNullOrEmpty(user.Permissions))
                {
                    userPermissions = JsonConvert.DeserializeObject <UserPermissionsContainer>(user.Permissions);
                }

                //apply permission to legacypermission tag of user details
                string attributeTag = "[" + permissionAttribute.ToString() + "=" + attributeValue + "];";

                if (userPermissions.LegacyPermissions == null)
                {
                    userPermissions.LegacyPermissions = "";
                }
                if (userPermissions.Permissions == null)
                {
                    userPermissions.Permissions = new List <UserPermission>();
                }

                if (!removeOnly)
                {
                    //add permission

                    //append permission attribute for user

                    //legacy format is [AttributeName1=Value];[AttributeName2=Value]; -legacy  format is maintained as LegacyPermissions  field in JSON format, for older apps (mainly older versions of OCM app)
                    if (!userPermissions.LegacyPermissions.Contains(attributeTag))
                    {
                        if (!userPermissions.LegacyPermissions.EndsWith(";") && userPermissions.LegacyPermissions != "")
                        {
                            userPermissions.LegacyPermissions += ";";
                        }
                        userPermissions.LegacyPermissions += attributeTag;

                        //add permission to main permission list
                        if (permissionAttribute == StandardPermissionAttributes.CountryLevel_Editor)
                        {
                            var permission = new UserPermission();
                            if (attributeValue != "All")
                            {
                                permission.CountryID = int.Parse(attributeValue);
                            }
                            permission.Level = PermissionLevel.Editor;
                            userPermissions.Permissions.Add(permission);
                        }

                        //TODO: administrator permissions
                        AuditLogManager.Log(administrator, AuditEventType.PermissionGranted, "User: "******"; Permission:" + permissionAttribute.ToString(), null);
                    }
                }
                else
                {
                    //remove permission
                    userPermissions.LegacyPermissions = userPermissions.LegacyPermissions.Replace(attributeTag, "");

                    if (permissionAttribute == StandardPermissionAttributes.CountryLevel_Editor)
                    {
                        if (attributeValue != "All")
                        {
                            int countryID = int.Parse(attributeValue);
                            userPermissions.Permissions.RemoveAll(p => p.Level == PermissionLevel.Editor && p.CountryID == countryID);
                        }
                        else
                        {
                            userPermissions.Permissions.RemoveAll(p => p.Level == PermissionLevel.Editor);
                        }
                    }
                    AuditLogManager.Log(administrator, AuditEventType.PermissionRemoved, "User: "******"; Permission:" + permissionAttribute.ToString(), null);
                }

                //remove requested permission attribute if it exists
                if (userDetails.PermissionsRequested != null)
                {
                    userDetails.PermissionsRequested = userDetails.PermissionsRequested.Replace(attributeTag, "");
                }

                userDetails.Permissions = JsonConvert.SerializeObject(userPermissions, Formatting.None, new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore
                });
                dataModel.SaveChanges();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #29
0
 partial void DeleteUserPermission(UserPermission instance);
Beispiel #30
0
        public void ConvertUserPermissions()
        {
            //perform batch upgrade of all user permisions to include JSON formatted permissions and legacy format string
            var userList = dataModel.Users.Where(u => u.Permissions != null);

            foreach (var user in userList)
            {
                if (!user.Permissions.Contains("{"))
                {
                    List <UserPermission> permissions = new List <UserPermission>();

                    //parse permissions
                    var pList = user.Permissions.Split(';');
                    foreach (var p in pList)
                    {
                        var legacyPermission = p.Trim();
                        if (!String.IsNullOrEmpty(legacyPermission))
                        {
                            var permission = new UserPermission();
                            //[CountryLevel_Editor=All];[Administrator=true];
                            bool parsedOK = false;
                            if (legacyPermission.StartsWith("[CountryLevel_Editor"))
                            {
                                permission.Level = PermissionLevel.Editor;
                                if (!legacyPermission.Contains("=All"))
                                {
                                    var countryIDString = legacyPermission.Substring(p.IndexOf("=") + 1, legacyPermission.IndexOf("]") - (legacyPermission.IndexOf("=") + 1));
                                    permission.CountryID = int.Parse(countryIDString);
                                }
                                parsedOK = true;
                            }

                            if (legacyPermission.StartsWith("[Administrator=true]"))
                            {
                                permission.Level = PermissionLevel.Admin;
                                parsedOK         = true;
                            }

                            if (!parsedOK)
                            {
                                throw new Exception("Failed to parse permission: User" + user.ID + " :" + user.Permissions);
                            }
                            else
                            {
                                permissions.Add(permission);
                            }
                        }
                    }

                    UserPermissionsContainer allPermissions = new UserPermissionsContainer()
                    {
                        LegacyPermissions = user.Permissions, //preserve permissions string for legacy users
                        Permissions       = permissions       //express permission as a list of permission objects
                    };

                    user.Permissions = JsonConvert.SerializeObject(allPermissions, Formatting.None, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    });
                }
            }

            dataModel.SaveChanges();
        }
 static void PermissionNew(UserPermission sender, NewEventArgs e)
 {
     InvalidateCacheForPermissionsChange(sender);
 }
Beispiel #32
0
        public IActionResult AuthorizeUser(List <int> authorizeSelect, string selected, string deleteSelect, int userId)
        {
            var role = from s in (_roleService.GetRolesByUserId(_workContext.CurrentUser.Id).ToList()) select s.Name;

            if (role.Contains("超级管理员") || _permissionService.Authorize("UpdateRolePermission"))
            {
                try
                {
                    var add = new List <UserPermission>();
                    if (!string.IsNullOrEmpty(selected))
                    {
                        var ed             = selected.Split(';').Select(x => x).Where(x => !IsNullOrEmpty(x)).ToArray();
                        var authorizedList = Array.ConvertAll(ed, int.Parse);
                        //批量增加权限
                        foreach (var au in authorizeSelect)
                        {
                            if (!authorizedList.Any(p => p == au))
                            {
                                var temp = new UserPermission
                                {
                                    UserId       = userId,
                                    PermissionId = au,
                                    Isvalid      = true
                                };
                                add.Add(temp);
                            }
                        }
                    }
                    else
                    {
                        foreach (var au in authorizeSelect)
                        {
                            var temp = new UserPermission
                            {
                                UserId       = userId,
                                PermissionId = au,
                                Isvalid      = true
                            };
                            add.Add(temp);
                        }
                    }
                    _userPermissionService.AddRangeUserPermission(add);
                }
                catch (Exception e)
                {
                    return(Error());
                }

                try
                {
                    if (!string.IsNullOrEmpty(deleteSelect))
                    {
                        //待删除的权限
                        var ing        = deleteSelect.Split(';').Select(t => t).Where(t => !IsNullOrEmpty(t)).ToArray();
                        var deleteList = Array.ConvertAll(ing, int.Parse);

                        var del = new List <UserPermission>();
                        foreach (var de in deleteList)
                        {
                            var temp = _userPermissionService.GetPermission(userId, de);
                            if (temp != null)
                            {
                                del.Add(temp);
                            }
                        }
                        if (del.Count > 0)
                        {
                            _userPermissionService.DelRangeUserPermission(del);
                        }
                    }
                }
                catch (Exception e)
                {
                    return(Error());
                }

                return(Success());
            }
            else
            {
                return(Error("无操作权限!"));
            }
        }
Beispiel #33
0
 private void SetUserEmailPemission(int userId)
 {
     UserPermission up = new UserPermission();
     up.date = DateTime.Now.Date;
     up.permissionId = (int)Enums.Permissions.EmailPermission;
     up.status = true;
     up.userId = userId;
     PostAroundServiceClient client = new PostAroundServiceClient();
     int response = client.SetUserPermission(up);
     client.Close();
 }
Beispiel #34
0
        private void Search()
        {
            try
            {
                int companyCode = int.Parse(GetCompany());

                List <MembershipUser> listUser = new List <MembershipUser>();


                List <UserPermission> listAllPermisson = UserPermission.GetAll();

                foreach (MembershipUser m in Membership.GetAllUsers())
                {
                    if (Common.isAdminAccount(m.UserName))
                    {
                        continue;
                    }
                    UserPermission findUser = listAllPermisson.FirstOrDefault(p => p.Username == m.UserName);
                    if (findUser == null || findUser.CompanyId == companyCode)
                    {
                        listUser.Add(m);
                    }
                }
                listUser = listUser.Where(l => (l.UserName.Contains(txtUserName.Text))).ToList();
                List <MembershipUser> onlineUser = new List <MembershipUser>();
                foreach (MembershipUser u in listUser)
                {
                    if (u.IsOnline)
                    {
                        onlineUser.Add(u);
                    }
                }

                if (cbxOnlineUser.Checked)
                {
                    if (onlineUser.Count == 0)
                    {
                        lblNoRecord.Visible = true;
                        DataTable dt = new DataTable();
                        dt.Columns.Add("UserName");
                        dt.Columns.Add("Email");
                        dt.Columns.Add("IsApproved");
                        DataRow r = dt.NewRow();
                        r["UserName"]   = string.Empty;
                        r["Email"]      = string.Empty;
                        r["IsApproved"] = true;
                        dt.Rows.Add(r);
                        grvUser.DataSource = dt;
                        grvUser.DataBind();
                        grvUser.Rows[0].Visible = false;
                    }
                    else
                    {
                        lblNoRecord.Visible = false;
                        grvUser.DataSource  = onlineUser;
                        grvUser.DataBind();
                    }
                }
                else
                {
                    if (listUser.Count == 0)
                    {
                        lblNoRecord.Visible = true;
                        DataTable dt = new DataTable();
                        dt.Columns.Add("UserName");
                        dt.Columns.Add("Email");
                        dt.Columns.Add("IsApproved");
                        DataRow r = dt.NewRow();
                        r["UserName"]   = string.Empty;
                        r["Email"]      = string.Empty;
                        r["IsApproved"] = true;
                        dt.Rows.Add(r);

                        grvUser.DataSource = dt;
                        grvUser.DataBind();
                        grvUser.Rows[0].Visible = false;
                    }
                    else
                    {
                        lblNoRecord.Visible = false;
                        grvUser.DataSource  = listUser;
                        grvUser.DataBind();
                    }
                }


                LinkButton lBtn          = new LinkButton();
                LinkButton lBtnResetPass = new LinkButton();
                foreach (GridViewRow r in grvUser.Rows)
                {
                    lBtn          = (LinkButton)r.Cells[3].FindControl("lBtnLockUnLock");
                    lBtnResetPass = (LinkButton)r.Cells[4].FindControl("lBtnResetPassword");

                    if (r.Cells[2].Text == "False")
                    {
                        r.Cells[2].Text = string.Empty;
                        lBtn.Text       = GetResource("Approve");
                    }
                    else
                    {
                        r.Cells[2].Text = "√";
                        lBtn.Text       = GetResource("Disapprove");
                    }
                    if (r.Cells[0].Text == this.User.Identity.Name)
                    {
                        lBtn.Visible = false;
                    }

                    lBtnResetPass.Text = GetResource("ResetPassword");

                    lBtn.Attributes["onclick"]          = "javascript:return confirm('" + string.Format(GetResource("msDisapproveAccount"), lBtn.Text, Common.GetRowString(r.Cells[0].Text)) + "');";
                    lBtnResetPass.Attributes["onclick"] = "javascript:return confirm('" + string.Format(GetResource("msResetPassword"), Common.GetRowString(r.Cells[0].Text)) + "');";


                    UserPermission user = UserPermission.GetUserPermission(r.Cells[0].Text);
                    if (user != null)
                    {
                        DropDownList cbx = (DropDownList)r.Cells[5].FindControl("cbxPermission");
                        if (!string.IsNullOrEmpty(user.WebPermission))
                        {
                            cbx.SelectedValue = user.WebPermission;
                        }
                        else
                        {
                            cbx.SelectedIndex = 0;
                        }

                        CheckBox chkApp = (CheckBox)r.Cells[6].FindControl("cboAppPermission");
                        chkApp.Checked = user.AppPermission;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error Search", ex);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert(\"" + GetJSMessage(GetResource("Title_Error"), ex.Message) + "\");", true);
            }
        }
    public int SetUserPermission(UserPermission up)
    {
        int retVal = 0;

        UserPermissionsTableAdapter adapter = new UserPermissionsTableAdapter();
        Object obj = adapter.SetUserPermission(up.userId, up.permissionId, up.status);

        if (obj != null)
        {
            retVal = Convert.ToInt32(obj);
        }

        return retVal;
    }
 public void Add(UserPermission permission)
 {
     _permissionDal.Add(permission);
 }
Beispiel #37
0
 public void SaveUserPermission(UserPermission userPermission)
 {
     var perms = EngineContext.Current.Resolve<IRepository<UserPermission, int>>();
     perms.SaveOrUpdate(userPermission);
 }
 public void Delete(UserPermission permission)
 {
     _permissionDal.Delete(permission);
 }
 public virtual void CreateUserPermission(UserPermission entity)
 {
     Create(entity);
 }
 public void Update(UserPermission permission)
 {
     _permissionDal.Update(permission);
 }
 public virtual void DeleteUserPermission(UserPermission entity)
 {
     Delete(entity);
 }
        private void Button_AddUserPermission(object sender, RoutedEventArgs e)
        {
            //error handling
            if (activeProject == null)
            {
                MessageBox.Show("Please select a Project", "Error"
                                , MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (activeFolder == null)
            {
                MessageBox.Show("Please select a Folder", "Error"
                                , MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (FolderUserPermissionComboBox.SelectedItem == null)
            {
                MessageBox.Show("Please select a Userpermission", "Error"
                                , MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var tobeadd = InputUserEmail.Text.Split(';');

            if (tobeadd.Any(iter => string.IsNullOrWhiteSpace(iter)))
            {
                MessageBox.Show("Please enter a valid Name.\nMaybe an ; to much?", "Error"
                                , MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }


            var inputindsrole = InputIndustryRole.Text.Split(';');
            var roletoadd     = inputindsrole.Where(iterrole =>
                                                    !string.IsNullOrWhiteSpace(iterrole)).ToList();


            //add user
            foreach (var iteruser in tobeadd)
            {
                var tmp = new UserPermission(iteruser.Trim(), (AccessPermissionEnum)
                                             FolderUserPermissionComboBox.SelectedItem);
                activeFolder.UserPermissions.Add(tmp);
                tmp.AssignedUsers.IndustryRoles = roletoadd;

                //if no company was added
                if ((string.IsNullOrWhiteSpace(InputCompanyName.Text)) ||
                    (InputCompanyName.Text.Equals("add company name here")))
                {
                    continue;
                }

                tmp.AssignedUsers.AssignedCompany = new Company(InputCompanyName.Text);
                //assign Trade to Company
                if (TradeComboBox.SelectionBoxItem.ToString() != "")
                {
                    tmp.AssignedUsers.AssignedCompany.Trade = SelectionManager.SelectTrade(
                        (string)TradeComboBox.SelectionBoxItem);
                }
            }
            //refresh view
            UserPermissionView.Items.Refresh();
        }
    //获取
    public static string GetItem(Page page)
    {
        DataTable dt = new DataTable();

        //dt = UserPermission.GetModulesByLevel(ModuleLevel.All);

        if (HttpContext.Current.Application["Administrator"].ToString().Contains(UserSession.Current.UserAccount.ToLower()))
        {
            //dt = UserPermission.GetModulesByLevel(ModuleLevel.All);
            dt = UserPermission.GetModulesByLevelByAll(ModuleLevel.All);
        }
        else
        {
            dt = new UserPermission(UserSession.Current.UserAccount).GetModulesByLevelWithRight(ModuleLevel.All);
        }

        string munestr = "";
        DataRow[] TopMenuRows;
        string strCHorEN = string.Empty;
        TopMenuRows = dt.Select("Menu_Level=1", "Menu_OrderID asc");

        for (int i = 0; i < TopMenuRows.Length; i++)
        {
            DataRow[] SubMenuRows = dt.Select("Parent_MenuId=" + TopMenuRows[i]["Menu_ID"].ToString().Trim(), "Menu_OrderID asc");

            if (munestr == "")
            {
                munestr += "\"" + TopMenuRows[i]["Menu_Name"].ToString().Trim() + "|" + TopMenuRows[i]["Menu_ID"].ToString().Trim() + "\":";
            }
            else
            {
                munestr += ",\"" + TopMenuRows[i]["Menu_Name"].ToString().Trim() + "|" + TopMenuRows[i]["Menu_ID"].ToString().Trim() + "\":";
            }
            if (SubMenuRows.Length <= 0)//if there is no submenu,the top menue needn't to display
            {
                munestr += "\"\"";
                continue;
            }
            for (int j = 0; j < SubMenuRows.Length; j++)
            {
                if (j == 0)
                {
                    munestr += "\"" + SubMenuRows[j]["Menu_Name"].ToString().Trim() + "|" + SubMenuRows[j]["Menu_Url"].ToString().Trim() + "|" + SubMenuRows[j]["Menu_ID"].ToString().Trim();
                }
                else
                {
                    munestr += "," + SubMenuRows[j]["Menu_Name"].ToString().Trim() + "|" + SubMenuRows[j]["Menu_Url"].ToString().Trim() + "|" + SubMenuRows[j]["Menu_ID"].ToString().Trim();

                }
                DataRow[] SecondMenuRows = dt.Select("Parent_MenuId=" + SubMenuRows[j]["Menu_ID"].ToString().Trim(), "Menu_OrderID asc");
                if (SecondMenuRows.Length > 0)
                {
                    for (int k = 0; k < SecondMenuRows.Length; k++)
                    {
                        munestr += "*" + SecondMenuRows[k]["Menu_Name"].ToString().Trim() + "|" + SecondMenuRows[k]["Menu_Url"].ToString().Trim() + "|" + SecondMenuRows[k]["Menu_ID"].ToString().Trim();
                    }
                }

            }
            if (SubMenuRows.Length > 0)//if there no content ,needn't to add the end "
            {
                munestr += "\"";
            }
        }
        return "{" + munestr + "}";//the new memu tree
    }
Beispiel #44
0
        private XElement BuildViewString(EmployeeInfo currentEmployeeInfo, string departmentId, string vehicleId)
        {
            EmployeeRole currentUserRole = UserPermission.GetCurrentUserRole(currentEmployeeInfo);
            XElement     filterElement   = null;

            string fromDate      = this.Page.Request.Params.Get("AdminFromDate");
            string fromDateValue = $"{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}";

            if (!string.IsNullOrEmpty(fromDate))
            {
                DateTime dtFromDate;
                bool     isValidFromDate = DateTime.TryParseExact(fromDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dtFromDate);
                if (isValidFromDate)
                {
                    fromDateValue = $"{dtFromDate:yyyy-MM-dd}";
                }
            }

            string toDate      = this.Page.Request.Params.Get("AdminToDate");
            string toDateValue = $"{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}";

            if (!string.IsNullOrEmpty(toDate))
            {
                DateTime dtToDate;
                bool     isValidToDate = DateTime.TryParseExact(toDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dtToDate);
                if (isValidToDate)
                {
                    toDateValue = $"{dtToDate:yyyy-MM-dd};";
                }
            }

            string filterStr = $@"<And>
                                    <Geq>
                                        <FieldRef Name='TransportTime' />
                                        <Value IncludeTimeValue='FALSE' Type='DateTime'>{fromDateValue}</Value>
                                    </Geq>
                                    <Leq>
                                        <FieldRef Name='TransportTime' />
                                        <Value IncludeTimeValue='FALSE' Type='DateTime'>{toDateValue}</Value>
                                    </Leq>
                                </And>";

            string deptFilterStr = @"<Eq>
                                        <FieldRef Name='CommonDepartment' LookupId='TRUE'/>
                                        <Value Type='Lookup'>{DepartmentId}</Value>
                                    </Eq>";

            string vehicleFilterStr = @"<Eq>
                                        <FieldRef Name='VehicleLookup' LookupId='TRUE'/>
                                        <Value Type='Lookup'>{VehicleId}</Value>
                                    </Eq>";

            if (currentUserRole == EmployeeRole.BOD || currentUserRole == EmployeeRole.AdminOfHR || currentUserRole == EmployeeRole.DepartmentHeadOfHR)
            {
                if (!string.IsNullOrEmpty(departmentId) && !departmentId.Trim().Equals("0"))
                {
                    filterStr = string.Format("<And>{0}{1}</And>", deptFilterStr, filterStr);
                }

                if (!string.IsNullOrEmpty(vehicleId) && !vehicleId.Trim().Equals("0"))
                {
                    filterStr = string.Format("<And>{0}{1}</And>", vehicleFilterStr, filterStr);
                }
            }

            filterStr = $@"<And>{filterStr}<Eq><FieldRef Name='CommonLocation' LookupId='TRUE'/><Value Type='Lookup'>{currentEmployeeInfo.FactoryLocation.LookupId}</Value></Eq></And>";

            if (currentUserRole != EmployeeRole.BOD && currentUserRole == EmployeeRole.AdminOfHR)
            {
                filterStr = string.Format(@"<And>{0}<Eq><FieldRef Name='ApprovalStatus' /><Value Type='Text'>Approved</Value></Eq></And>", filterStr);
            }

            filterElement = XElement.Parse(filterStr);

            return(filterElement);
        }
 public UserPermission Add(UserPermission entity)
 {
     return _userPermissionStorageApplication.Add(entity);
 }
Beispiel #46
0
        private void ChangePermission( GridViewRow r , bool webPermission)
        {
            try
            {
                UserPermission userper = UserPermission.GetUserPermission(r.Cells[0].Text);
                if (userper == null)
                {
                    userper = new UserPermission();
                }
                userper.CompanyId = int.Parse(GetCompany());
                if (webPermission == true)
                {
                    DropDownList cbx = new DropDownList();
                    cbx = (DropDownList)r.Cells[0].FindControl("cbxPermission");
                    if (cbx.SelectedValue == string.Empty)
                        userper.WebPermission = null;
                    else
                        userper.WebPermission = cbx.SelectedItem.Value;
                }
                else
                {
                    CheckBox cbx = new CheckBox();
                    cbx = (CheckBox)r.Cells[0].FindControl("cboAppPermission");
                    userper.AppPermission = cbx.Checked;
                }

                if (userper.Username == null)
                {
                    userper.Username = r.Cells[0].Text;
                    userper.CreateAccount = this.User.Identity.Name;
                    userper.Insert();
                }
                else
                {
                    userper.ModifiedAccount = this.User.Identity.Name;
                    userper.Update();
                }
                Search();
            }
            catch (Exception ex)
            {
                logger.Error("Error ChangePermission ", ex);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "alert(\"" + GetJSMessage(GetResource("Title_Error"), ex.Message) + "\");", true);
            }
        }
 public void Update(UserPermission entity)
 {
     _userPermissionStorageApplication.Update(entity);
 }
Beispiel #48
0
        public void CreateUser(UsersObject newUser)
        {
            CPDatabase database  = null;
            ADGroup    ldapGroup = null;
            ADUser     ldapUser  = null;

            CloudPanelTransaction newUserTransaction = new CloudPanelTransaction();

            try
            {
                // Insert into database
                database = new CPDatabase();

                // Make sure the user doesn't already exist
                var foundUser = (from u in database.Users
                                 where u.UserPrincipalName == newUser.UserPrincipalName
                                 select u).FirstOrDefault();

                if (foundUser != null)
                {
                    ThrowEvent(AlertID.FAILED, "User already exists " + newUser.UserPrincipalName);
                }
                else
                {
                    // Get the company's OU where we need to save the user
                    var companyDistinguishedName = (from c in database.Companies
                                                    where !c.IsReseller
                                                    where c.CompanyCode == newUser.CompanyCode
                                                    select c.DistinguishedName).First();

                    // Check if they are using a custom user's OU
                    if (!string.IsNullOrEmpty(StaticSettings.UsersOU))
                    {
                        companyDistinguishedName = string.Format("OU={0},{1}", StaticSettings.UsersOU, companyDistinguishedName);
                    }

                    ldapUser = new ADUser(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                    UsersObject createdUser = ldapUser.NewUser(newUser, companyDistinguishedName, StaticSettings.AllowCustomNameAttribute);
                    newUserTransaction.NewUser(createdUser.UserPrincipalName);

                    // Add the users to the groups
                    ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                    ldapGroup.AddMember("AllUsers@" + newUser.CompanyCode, createdUser.UserPrincipalName, "upn");

                    if (newUser.IsCompanyAdmin)
                    {
                        ldapGroup.AddMember("Admins@" + newUser.CompanyCode, createdUser.UserPrincipalName, "upn");
                    }

                    // Insert into database
                    User sqlUser = new User();
                    sqlUser.UserGuid          = createdUser.UserGuid;
                    sqlUser.CompanyCode       = createdUser.CompanyCode;
                    sqlUser.sAMAccountName    = createdUser.sAMAccountName;
                    sqlUser.UserPrincipalName = createdUser.UserPrincipalName;
                    sqlUser.DistinguishedName = createdUser.DistinguishedName;
                    sqlUser.DisplayName       = createdUser.DisplayName;
                    sqlUser.Firstname         = createdUser.Firstname;
                    sqlUser.Middlename        = createdUser.Middlename;
                    sqlUser.Lastname          = createdUser.Lastname;
                    sqlUser.Email             = string.Empty;
                    sqlUser.Department        = createdUser.Department;
                    sqlUser.IsResellerAdmin   = createdUser.IsResellerAdmin;
                    sqlUser.IsCompanyAdmin    = createdUser.IsCompanyAdmin;
                    sqlUser.MailboxPlan       = 0;
                    sqlUser.TSPlan            = 0;
                    sqlUser.LyncPlan          = 0;
                    sqlUser.Created           = DateTime.Now;
                    sqlUser.AdditionalMB      = 0;
                    sqlUser.ActiveSyncPlan    = 0;
                    database.Users.Add(sqlUser);

                    // Insert permissions into database
                    if (createdUser.IsCompanyAdmin)
                    {
                        UserPermission newPermissions = new UserPermission();
                        newPermissions.UserID                = sqlUser.ID;
                        newPermissions.EnableExchange        = createdUser.EnableExchangePerm;
                        newPermissions.DisableExchange       = createdUser.DisableExchangePerm;
                        newPermissions.AddDomain             = createdUser.AddDomainPerm;
                        newPermissions.DeleteDomain          = createdUser.DeleteDomainPerm;
                        newPermissions.EnableAcceptedDomain  = createdUser.EnableAcceptedDomainPerm;
                        newPermissions.DisableAcceptedDomain = createdUser.DisableAcceptedDomainPerm;
                        database.UserPermissions.Add(newPermissions);
                    }

                    database.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ThrowEvent(AlertID.FAILED, ex.Message);

                // Rollback on error
                newUserTransaction.RollBack();
            }
            finally
            {
                if (ldapUser != null)
                {
                    ldapUser.Dispose();
                }

                if (ldapGroup != null)
                {
                    ldapGroup.Dispose();
                }

                if (database != null)
                {
                    database.Dispose();
                }
            }
        }
 public virtual void CreateUserPermission(UserPermission entity)
 {
     entityDao.CreateUserPermission(entity);
 }
 public virtual void UpdateUserPermission(UserPermission entity)
 {
     entityDao.UpdateUserPermission(entity);
 }
Beispiel #51
0
        public void UpdateUser(UsersObject updateUser, bool isSuperOrResellerAdmin)
        {
            CPDatabase database  = null;
            ADGroup    ldapGroup = null;
            ADUser     ldapUser  = null;

            try
            {
                database = new CPDatabase();

                // Get the user from the database
                var foundUser = (from u in database.Users
                                 where u.UserPrincipalName == updateUser.UserPrincipalName
                                 select u).FirstOrDefault();

                if (foundUser == null)
                {
                    ThrowEvent(AlertID.FAILED, "Unknown user " + updateUser.UserPrincipalName);
                }
                else
                {
                    this.logger.Debug("Found user " + foundUser.UserPrincipalName + " in the database. Continuing...");

                    // Update the user values
                    foundUser.Firstname   = updateUser.Firstname;
                    foundUser.Middlename  = updateUser.Middlename;
                    foundUser.Lastname    = updateUser.Lastname;
                    foundUser.DisplayName = updateUser.DisplayName;
                    foundUser.Department  = updateUser.Department;

                    // Update user in Active Directory
                    ldapUser = new ADUser(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                    ldapUser.UpdateUser(updateUser, StaticSettings.AllowCustomNameAttribute);

                    // Only update these values if super admin or reseller admin is modifying the user
                    if (isSuperOrResellerAdmin)
                    {
                        this.logger.Debug("Super admin or reseller is updating user so we can check comapny admin permissions and reseller permissions");

                        foundUser.IsCompanyAdmin  = updateUser.IsCompanyAdmin;
                        foundUser.IsResellerAdmin = updateUser.IsResellerAdmin;

                        // Get permissions from database
                        var userPermissions = (from p in database.UserPermissions
                                               where p.UserID == foundUser.ID
                                               select p).FirstOrDefault();


                        // If the user is no longer a company admin then remove permissions from the database
                        if (userPermissions != null && !updateUser.IsCompanyAdmin)
                        {
                            this.logger.Debug("User " + updateUser.UserPrincipalName + " is no longer a comapny admin. Need to remove rights from database and security group");

                            database.UserPermissions.Remove(userPermissions);

                            // Remove from Admins@ security group
                            ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                            ldapGroup.RemoveMember("Admins@" + updateUser.CompanyCode, updateUser.UserPrincipalName, "upn");
                        }
                        else if (userPermissions != null && updateUser.IsCompanyAdmin)
                        {
                            this.logger.Debug("User " + updateUser.UserPrincipalName + " is a company admin. Need to update company admin rights in database.");

                            // If user permissions was found and the user is company admin then update the values
                            userPermissions.EnableExchange        = updateUser.EnableExchangePerm;
                            userPermissions.DisableExchange       = updateUser.DisableExchangePerm;
                            userPermissions.AddDomain             = updateUser.AddDomainPerm;
                            userPermissions.DeleteDomain          = updateUser.DeleteDomainPerm;
                            userPermissions.EnableAcceptedDomain  = updateUser.EnableAcceptedDomainPerm;
                            userPermissions.DisableAcceptedDomain = updateUser.DisableAcceptedDomainPerm;
                        }
                        else if (userPermissions == null && updateUser.IsCompanyAdmin)
                        {
                            this.logger.Debug("User " + updateUser.UserPrincipalName + " does not have any existing company admin rights. We need to add them to the database.");

                            // No existing permissions were found and we need to add to database
                            userPermissions                       = new UserPermission();
                            userPermissions.UserID                = foundUser.ID;
                            userPermissions.EnableExchange        = updateUser.EnableExchangePerm;
                            userPermissions.DisableExchange       = updateUser.DisableExchangePerm;
                            userPermissions.AddDomain             = updateUser.AddDomainPerm;
                            userPermissions.DeleteDomain          = updateUser.DeleteDomainPerm;
                            userPermissions.EnableAcceptedDomain  = updateUser.EnableAcceptedDomainPerm;
                            userPermissions.DisableAcceptedDomain = updateUser.DisableAcceptedDomainPerm;
                            database.UserPermissions.Add(userPermissions);

                            // Add to Admins@ security group
                            ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                            ldapGroup.AddMember("Admins@" + updateUser.CompanyCode, updateUser.UserPrincipalName, "upn");
                        }
                    }
                    else
                    {
                        this.logger.Debug("User making changes to " + updateUser.UserPrincipalName + " is not a super admin or reseller admin. We cannot update company admin or reseller admin permissions unless the user making changes is a super or reseller admin.");
                    }

                    // Update database
                    database.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                this.logger.Debug("Error updating user " + updateUser.UserPrincipalName, ex);
                ThrowEvent(AlertID.FAILED, ex.Message);
            }
            finally
            {
                if (ldapUser != null)
                {
                    ldapUser.Dispose();
                }

                if (ldapGroup != null)
                {
                    ldapGroup.Dispose();
                }

                if (database != null)
                {
                    database.Dispose();
                }
            }
        }
Beispiel #52
0
 /// <summary>
 /// Fill External Childs of UserPermission Object.
 /// </summary>
 /// <param name="userPermissionObject"></param>
 /// <returns></returns>
 public void FillChilds(UserPermission userPermissionObject)
 {
     ///Fill external information of Childs of UserPermissionObject
 }
 public virtual void DeleteUserPermission(UserPermission entity)
 {
     entityDao.DeleteUserPermission(entity);
 }
 public virtual void InsertUserPermission(UserPermission userPermission)
 {
     InsertObject(userPermission);
 }
 public UserPermissionAttribute(UserPermission userPermission)
 {
     this.UserPermission = userPermission;
 }
 /// <summary>
 /// Clear all session and redirect home page
 /// </summary>
 protected void OnLogout()
 {
     UserPermission.SetEmployeeInfo(null);
     //Response.Redirect(StringConstant.PageLoginURL);
     SPUtility.Redirect(StringConstant.PageLoginURL, SPRedirectFlags.DoNotEndResponse | SPRedirectFlags.Trusted, HttpContext.Current);
 }
Beispiel #57
0
 partial void UpdateUserPermission(UserPermission instance);
 static void PermissionUpdated(UserPermission sender, SaveEventArgs e)
 {
     InvalidateCacheForPermissionsChange(sender);
 }
Beispiel #59
0
        // 查询
        private static int GetPrivacy( User user, UserPermission up )
        {
            int defaultValue = UserPrivacy.GetDefaultValue();

            String securityStr = user.Security;

            if (strUtil.IsNullOrEmpty( securityStr )) return defaultValue; //默认值

            Dictionary<string, int> settings = getSettingValueByString( securityStr );

            int val = defaultValue;//默认值
            if (settings.ContainsKey( up.ToString() )) val = settings[up.ToString()];

            return val;
        }
Beispiel #60
0
 partial void InsertUserPermission(UserPermission instance);