Ejemplo n.º 1
0
        protected void LoginControll_LoggedIn(object sender, EventArgs e)
        {
            var targetUrl = GetPostLoginUrl();
            var userName  = ((Login)sender).UserName;

            if (this._ssoEnabled)
            {
                this.GetCookie().Value = CryptoApi.Crypt(userName, "sensenet60beta1", "SenseNetContentRepository");
            }

            if (OnUserLoggedIn != null)
            {
                OnUserLoggedIn(sender, e);
            }

            SnLog.WriteAudit(AuditEvent.LoginSuccessful,
                             new Dictionary <string, object>
            {
                { "UserName", userName },
                { "ClientAddress", RepositoryTools.GetClientIpAddress() }
            });

            LoginExtender.OnLoggedIn(new LoginInfo {
                UserName = userName
            });

            HttpContext.Current.Response.Redirect(targetUrl);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Logs out the current user.
        /// </summary>
        /// <param name="ultimateLogout">Whether this should be an ultimate logout. If set to True, the user will be logged out from all clients.</param>
        public static void Logout(bool ultimateLogout = false)
        {
            var user = User.Current;
            var info = new CancellableLoginInfo {
                UserName = user.Username
            };

            LoginExtender.OnLoggingOut(info);

            if (info.Cancel)
            {
                return;
            }

            FormsAuthentication.SignOut();

            AccessTokenVault.DeleteTokensByUser(user.Id);

            SnLog.WriteAudit(AuditEvent.Logout,
                             new Dictionary <string, object>
            {
                { "UserName", user.Username },
                { "ClientAddress", RepositoryTools.GetClientIpAddress() }
            });

            LoginExtender.OnLoggedOut(new LoginInfo {
                UserName = user.Username
            });

            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Session != null)
                {
                    HttpContext.Current.Session.Abandon();
                }

                // remove session cookie
                var sessionCookie = new HttpCookie(GetSessionIdCookieName(), string.Empty)
                {
                    Expires = DateTime.UtcNow.AddDays(-1)
                };

                HttpContext.Current.Response.Cookies.Add(sessionCookie);

                // in case of ultimate logout saves the time on user
                if (ultimateLogout || Configuration.Security.DefaultUltimateLogout)
                {
                    using (new SystemAccount())
                    {
                        if (user is User userNode)
                        {
                            userNode.LastLoggedOut = DateTime.UtcNow;
                            userNode.Save(SavingMode.KeepVersion);
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Current user transfers the lock ownership to the target user.
        /// If target user is null, it will be the current user.
        /// Current user must have ForceCheckin permission.
        /// </summary>
        /// <param name="targetUser">Target user or null.</param>
        public void TakeLockOver(IUser targetUser)
        {
            _node.Security.Assert(PermissionType.ForceCheckin);

            if (targetUser == null)
            {
                targetUser = AccessProvider.Current.GetCurrentUser();
            }

            if (targetUser.Id == this.Node.LockedById)
            {
                return;
            }

            if (!_node.Locked)
            {
                throw new ApplicationException("TakeLockOver is invalid action if the content is not locked.");
            }

            if (!_node.Security.HasPermission(targetUser, PermissionType.Save))
            {
                throw new ApplicationException("Cannot transfer the document's checked out state to the target user because he or she does not have enough permissions to save the document.");
            }

            var oldLockerId = this.Node.LockedById;

            var auditProperties = new Dictionary <string, object>
            {
                { "Id", _node.Id },
                { "Path", _node.Path },
                { "OldLockerId", oldLockerId },
                { "NewLockerId", targetUser.Id }
            };

            using (var audit = new AuditBlock(AuditEvent.LockTakenOver, "Trying to take lock over.", auditProperties))
            {
                using (var op = SnTrace.ContentOperation.StartOperation("Node.LockHandler.TakeLockOver: NodeId:{0}, VersionId:{1}, Version:{2}, UserId:{3}, UserName:{4}.", _node.Id, _node.VersionId, _node.Version, targetUser.Id, targetUser.Username))
                {
                    if (_node.LockedById != targetUser.Id)
                    {
                        _node.LockToken      = Guid.NewGuid().ToString();
                        _node.LockedById     = targetUser.Id;
                        _node.LockDate       = DateTime.UtcNow;
                        _node.LastLockUpdate = DateTime.UtcNow;
                        _node.LockTimeout    = RepositoryEnvironment.DefaultLockTimeout;

                        _node.Save(VersionRaising.None, VersionStatus.Locked, true);
                    }

                    SnLog.WriteAudit(AuditEvent.LockTakenOver, auditProperties);

                    op.Successful = true;
                }
                audit.Successful = true;
            }
        }
Ejemplo n.º 4
0
 protected void LoginStatus_LoggedOut(object sender, EventArgs e)
 {
     SnLog.WriteAudit(AuditEvent.Logout,
                      new Dictionary <string, object>
     {
         { "UserName", User.Current.Username },
         { "ClientAddress", RepositoryTools.GetClientIpAddress() }
     });
     if (OnUserLoggedOut != null)
     {
         OnUserLoggedOut(sender, e);
     }
     LoginExtender.OnLoggedOut(new LoginInfo {
         UserName = User.Current.Username
     });
 }
Ejemplo n.º 5
0
        public static void Logout()
        {
            var info = new CancellableLoginInfo {
                UserName = User.Current.Username
            };

            LoginExtender.OnLoggingOut(info);

            if (info.Cancel)
            {
                return;
            }

            FormsAuthentication.SignOut();

            SnLog.WriteAudit(AuditEvent.Logout,
                             new Dictionary <string, object>
            {
                { "UserName", User.Current.Username },
                { "ClientAddress", RepositoryTools.GetClientIpAddress() }
            });

            LoginExtender.OnLoggedOut(new LoginInfo {
                UserName = User.Current.Username
            });

            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Session != null)
                {
                    HttpContext.Current.Session.Abandon();
                }

                // remove session cookie
                var sessionCookie = new HttpCookie(GetSessionIdCookieName(), string.Empty)
                {
                    Expires = DateTime.UtcNow.AddDays(-1)
                };

                HttpContext.Current.Response.Cookies.Add(sessionCookie);
            }
        }
Ejemplo n.º 6
0
        protected void Login_LoginError(object sender, EventArgs e)
        {
            var login = sender as Login;

            var    userNameControl = this.FindControlRecursive("UserName");
            var    userNameTextBox = userNameControl as TextBox;
            string userName        = null;

            if (userNameTextBox != null)
            {
                userName = userNameTextBox.Text;
                if (!userName.Contains("\\"))
                {
                    // add default domain for logging reasons
                    var domain = (string.IsNullOrEmpty(this.DefaultDomain)
                        ? IdentityManagement.DefaultDomain
                        : this.DefaultDomain)
                                 ?? string.Empty;

                    userName = string.Concat(domain, "\\", userName);
                }

                SnLog.WriteAudit(AuditEvent.LoginUnsuccessful,
                                 new Dictionary <string, object>
                {
                    { "UserName", userName },
                    { "ClientAddress", RepositoryTools.GetClientIpAddress() }
                });
            }

            var info = new LoginInfo {
                UserName = userName, Message = login.FailureText
            };

            LoginExtender.OnLoginError(info);
            _message = info.Message;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Executes all modifications.
        /// Current user must have SetPermissions permission on any modified entity.
        /// An Auditlog record with changed data will be writen.
        /// OnPermissionChanging and OnPermissionChanged events are fired on any active NodeObserver that is not in the exclusion list (see "disabledObservers" parameter).
        /// </summary>
        /// <param name="disabledObservers">NodeObserver exclusion list.</param>
        public void Apply(List <Type> disabledObservers)
        {
            foreach (var entityId in this._acls.Keys)
            {
                this.Context.AssertPermission(entityId, PermissionType.SetPermissions);
            }
            using (var audit = new AuditBlock(AuditEvent.PermissionChanged, "Trying to execute permission modifications",
                                              new Dictionary <string, object>
            {
                { "Entities", this._acls.Count },
                { "Breaks", this._breaks.Count },
                { "Unbreaks", this._unbreaks.Count }
            }))
            {
                using (var op = SnTrace.Security.StartOperation("AclEditor.Apply (acl count: {0})", _acls.Count))
                {
                    string msg = null;
                    if ((msg = Validate(this._acls)) != null)
                    {
                        // Log the error, but allow the operation to continue, because acl editor
                        // may contain many different operations that we do not want to lose.
                        SnLog.WriteWarning("Invalid ACL: " + msg, EventId.Security);
                    }

                    var relatedEntities = new List <int>();
                    // collect related aces
                    var originalAces = new List <string>();
                    // changed acls
                    foreach (var entityId in this._acls.Keys)
                    {
                        relatedEntities.Add(entityId);
                        originalAces.Add(AcesToString(entityId, this.Context.GetExplicitEntries(entityId)));
                    }
                    // breaks that are not in changed aces
                    foreach (var entityId in this._breaks)
                    {
                        if (!this._acls.ContainsKey(entityId))
                        {
                            relatedEntities.Add(entityId);
                            originalAces.Add(AcesToString(entityId, this.Context.GetExplicitEntries(entityId)));
                        }
                    }
                    // unbreaks that are not in changed aces
                    foreach (var entityId in this._unbreaks)
                    {
                        if (!this._acls.ContainsKey(entityId))
                        {
                            relatedEntities.Add(entityId);
                            originalAces.Add(AcesToString(entityId, this.Context.GetExplicitEntries(entityId)));
                        }
                    }

                    var relatedNodeHeads = relatedEntities.Select(NodeHead.Get).ToArray();
                    var changedData      = new[] { new ChangedData {
                                                       Name = "SetPermissions", Original = originalAces
                                                   } };

                    // fire "before" event
                    var args1 = new CancellablePermissionChangingEventArgs(relatedNodeHeads, changedData);
                    using (var op1 = SnTrace.Security.StartOperation("AclEditor.Apply / FireOnPermissionChanging"))
                    {
                        NodeObserver.FireOnPermissionChanging(null, null, args1, disabledObservers);
                        if (args1.Cancel)
                        {
                            throw new CancelNodeEventException(args1.CancelMessage, args1.EventType, null);
                        }
                        op1.Successful = true;
                    }

                    var customData = args1.CustomData;

                    // main operation
                    base.Apply();

                    // collect new values
                    changedData[0].Value = relatedEntities.Select(x => AcesToString(x, this.Context.GetExplicitEntries(x))).ToList();

                    // fire "after" event
                    var args2 = new PermissionChangedEventArgs(relatedNodeHeads, customData, changedData);
                    using (var op2 = SnTrace.Security.StartOperation("AclEditor.Apply / FireOnPermissionChanged"))
                    {
                        NodeObserver.FireOnPermissionChanged(null, null, args2, disabledObservers);
                        op2.Successful = true;
                    }

                    // iterate through all edited entities and log changes one by one
                    for (var i = 0; i < relatedEntities.Count; i++)
                    {
                        var entity = relatedNodeHeads[i];
                        SnLog.WriteAudit(AuditEvent.PermissionChanged, new Dictionary <string, object>
                        {
                            { "Id", entity != null ? entity.Id : 0 },
                            { "Path", entity != null ? entity.Path : string.Empty },
                            { "Type", changedData[0].Name },
                            { "OldAcl", (changedData[0].Original as List <string>)[i] }, // changed data lists are in the same order as relatedentities
                            { "NewAcl", (changedData[0].Value as List <string>)[i] }
                        });
                    }
                    op.Successful = true;
                }
                audit.Successful = true;
            }
        }
Ejemplo n.º 8
0
        public static object Login(Content content, string username, string password)
        {
            if (string.IsNullOrEmpty(username))
            {
                Logout();
                throw new OData.ODataException(OData.ODataExceptionCode.Forbidden);
            }

            if (Membership.ValidateUser(username, password))
            {
                // we need to work with the full username that contains the domain: SetAuthCookie expects that
                if (!username.Contains("\\"))
                {
                    username = IdentityManagement.DefaultDomain + "\\" + username;
                }

                if (User.Current.IsAuthenticated)
                {
                    // if this is the user that is already logged in, return with a success code
                    if (string.CompareOrdinal(User.Current.Username, username) == 0)
                    {
                        using (new SystemAccount())
                        {
                            FormsAuthentication.SetAuthCookie(username, true);
                            return(Content.Create(User.Load(username) as User));
                        }
                    }

                    // logged in as a different user: we have to log out first
                    Logout();
                }

                var info = new CancellableLoginInfo {
                    UserName = username
                };
                LoginExtender.OnLoggingIn(info);
                if (info.Cancel)
                {
                    throw new OData.ODataException(OData.ODataExceptionCode.Forbidden);
                }

                SnLog.WriteAudit(AuditEvent.LoginSuccessful, new Dictionary <string, object>
                {
                    { "UserName", username },
                    { "ClientAddress", RepositoryTools.GetClientIpAddress() }
                });

                LoginExtender.OnLoggedIn(new LoginInfo {
                    UserName = username
                });


                using (new SystemAccount())
                {
                    FormsAuthentication.SetAuthCookie(username, true);
                    return(Content.Create(User.Load(username) as User));
                }
            }

            throw new OData.ODataException(OData.ODataExceptionCode.Forbidden);
        }