Esempio n. 1
0
        public void ChangePassword(int mailboxId, string password)
        {
            if (mailboxId < 0)
            {
                throw new ArgumentException(@"Invalid mailbox id.", "mailboxId");
            }

            var trimPwd = Parser.GetValidPassword(password);

            using (var daoFactory = new DaoFactory())
            {
                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                var serverMailboxAddresses = serverAddressDao.GetList(mailboxId);

                if (!serverMailboxAddresses.Any())
                {
                    throw new ArgumentException("Mailbox not found");
                }

                var serverMailboxAddress = serverMailboxAddresses.FirstOrDefault(a => !a.IsAlias && !a.IsMailGroup);

                if (serverMailboxAddress == null)
                {
                    throw new ArgumentException("Mailbox not found");
                }

                var mailboxDao = daoFactory.CreateMailboxDao();

                var exp = IsAdmin
                    ? (IMailboxExp) new ConcreteTenantMailboxExp(mailboxId, Tenant)
                    : new СoncreteUserMailboxExp(mailboxId, Tenant, User);

                var mailbox =
                    mailboxDao.GetMailBox(exp);

                if (mailbox == null) // Mailbox has been removed
                {
                    throw new ArgumentException("Mailbox not found");
                }

                var serverDao = daoFactory.CreateServerDao();

                var server = serverDao.Get(Tenant);

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                    engine.ChangePassword(mailbox.Address, trimPwd);

                    mailbox.Password     = trimPwd;
                    mailbox.SmtpPassword = trimPwd;

                    mailboxDao.SaveMailBox(mailbox);

                    tx.Commit();
                }
            }
        }
Esempio n. 2
0
        public void RemoveNotificationAddress(string address)
        {
            if (!CoreContext.Configuration.Standalone)
            {
                throw new SecurityException("Only for standalone");
            }

            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (string.IsNullOrEmpty(address))
            {
                throw new ArgumentNullException("address");
            }

            var deleteAddress = address.ToLowerInvariant().Trim();
            var notificationAddressSettings = ServerNotificationAddressSettings.LoadForTenant(Tenant);

            if (notificationAddressSettings.NotificationAddress != deleteAddress)
            {
                throw new ArgumentException("Mailbox not exists");
            }

            var mailAddress = new MailAddress(deleteAddress);

            using (var daoFactory = new DaoFactory())
            {
                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
                var serverDomain    = serverDomainDao.GetDomains().FirstOrDefault(d => d.Name == mailAddress.Host);

                if (serverDomain == null)
                {
                    throw new ArgumentException("Domain not exists");
                }

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                if (server == null)
                {
                    throw new ArgumentException("Server not configured");
                }

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                engine.RemoveMailbox(deleteAddress);
            }

            var addressSettings = notificationAddressSettings.GetDefault() as ServerNotificationAddressSettings;

            if (addressSettings != null && !addressSettings.SaveForTenant(Tenant))
            {
                throw new Exception("Could not delete notification address setting.");
            }
        }
Esempio n. 3
0
        public string GetServerVersion()
        {
            using (var daoFactory = new DaoFactory())
            {
                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                if (server == null)
                {
                    return(null);
                }

                var engine  = new Server.Core.ServerEngine(server.Id, server.ConnectionString);
                var version = engine.GetVersion();
                return(version);
            }
        }
        public void RemoveMailGroup(int id)
        {
            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (id < 0)
            {
                throw new ArgumentException(@"Invalid mailgroup id.", "id");
            }

            using (var daoFactory = new DaoFactory())
            {
                var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);

                var group = serverGroupDao.Get(id);

                if (group == null)
                {
                    throw new Exception("Group not found");
                }

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    serverGroupDao.Delete(id);

                    serverAddressDao.DeleteAddressesFromMailGroup(id);

                    serverAddressDao.Delete(group.AddressId);

                    engine.RemoveAlias(group.Address);

                    tx.Commit();
                }
            }

            CacheEngine.ClearAll();
        }
Esempio n. 5
0
        public void RemoveDomain(Entities.ServerDomain domain, bool skipMS = false)
        {
            try
            {
                using (var db = new DbManager(Defines.CONNECTION_STRING_NAME, Defines.RemoveDomainTimeout))
                {
                    var daoFactory = new DaoFactory(db);

                    using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                    {
                        var serverDomainDao = daoFactory.CreateServerDomainDao(domain.Tenant);

                        serverDomainDao.Delete(domain.Id);

                        if (!skipMS)
                        {
                            var serverDao = daoFactory.CreateServerDao();

                            var server = serverDao.Get(domain.Tenant);

                            if (server == null)
                            {
                                throw new Exception(string.Format("Information for Tenant's Mail Server not found (Tenant = {0})", domain.Tenant));
                            }

                            var serverEngine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                            serverEngine.RemoveDomain(domain.Name, false);
                        }

                        tx.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("RemoveDomainIfUseless(Domain: '{0}', ID='{1}') failed. Exception: {2}", domain.Name, domain.Id, ex.ToString()));
            }
        }
Esempio n. 6
0
        public void RemoveMailbox(MailBoxData mailBox)
        {
            var engine = new EngineFactory(mailBox.TenantId);

            using (var daoFactory = new DaoFactory())
            {
                var serverAddressDao = daoFactory.CreateServerAddressDao(mailBox.TenantId);

                var serverMailboxAddresses = serverAddressDao.GetList(mailBox.MailBoxId);

                var serverMailboxAddress = serverMailboxAddresses.FirstOrDefault(a => !a.IsAlias && !a.IsMailGroup);

                if (serverMailboxAddress == null)
                {
                    throw new InvalidDataException("Mailbox address not found");
                }

                var serverDomainDao = daoFactory.CreateServerDomainDao(mailBox.TenantId);
                var serverDomain    = serverDomainDao.GetDomain(serverMailboxAddress.DomainId);

                if (serverDomain == null)
                {
                    throw new InvalidDataException("Domain not found");
                }

                var serverGroupDao = daoFactory.CreateServerGroupDao(mailBox.TenantId);

                var serverGroups = serverGroupDao.GetList();

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(mailBox.TenantId);

                var serverEngine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                var utcNow = DateTime.UtcNow;

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    foreach (var serverGroup in serverGroups)
                    {
                        var addresses = serverAddressDao.GetGroupAddresses(serverGroup.Id);

                        var index = addresses.FindIndex(a => a.Id == serverMailboxAddress.Id);

                        if (index < 0)
                        {
                            continue;
                        }

                        addresses.RemoveAt(index);

                        if (addresses.Count == 0)
                        {
                            serverGroupDao.Delete(serverGroup.Id);

                            serverAddressDao.DeleteAddressesFromMailGroup(serverGroup.Id);

                            serverEngine.RemoveAlias(serverGroup.Address);
                        }
                        else
                        {
                            serverAddressDao.DeleteAddressFromMailGroup(serverGroup.Id, serverMailboxAddress.Id);

                            var goTo = string.Join(",",
                                                   addresses.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));

                            var serverAddress = new Alias
                            {
                                Name     = "",
                                Address  = serverGroup.Address,
                                GoTo     = goTo,
                                Domain   = serverDomain.Name,
                                IsActive = true,
                                IsGroup  = true,
                                Modified = utcNow,
                                Created  = serverGroup.DateCreated
                            };

                            serverEngine.SaveAlias(serverAddress);
                        }
                    }

                    serverAddressDao.Delete(serverMailboxAddresses.Select(a => a.Id).ToList());

                    foreach (var mailboxAddress in serverMailboxAddresses)
                    {
                        serverEngine.RemoveAlias(string.Format("{0}@{1}", mailboxAddress.AddressName, serverDomain.Name));
                    }

                    engine.MailboxEngine.RemoveMailBox(daoFactory, mailBox, false);

                    serverEngine.RemoveMailbox(string.Format("{0}@{1}", serverMailboxAddress.AddressName,
                                                             serverDomain.Name));

                    tx.Commit();
                }
            }
        }
Esempio n. 7
0
        public void RemoveAlias(int mailboxId, int addressId)
        {
            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (mailboxId < 0)
            {
                throw new ArgumentException(@"Invalid address id.", "mailboxId");
            }

            using (var daoFactory = new DaoFactory())
            {
                var mailboxDao = daoFactory.CreateMailboxDao();

                var mailbox = mailboxDao.GetMailBox(new ConcreteTenantServerMailboxExp(mailboxId, Tenant, false));

                if (mailbox == null)
                {
                    throw new ArgumentException("Mailbox not exists");
                }

                if (!mailbox.IsTeamlabMailbox)
                {
                    throw new ArgumentException("Invalid mailbox type");
                }

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                var alias = serverAddressDao.Get(addressId);

                if (!alias.IsAlias)
                {
                    throw new ArgumentException("Address is not alias");
                }

                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
                var serverDomain    = serverDomainDao.GetDomain(alias.DomainId);

                if (serverDomain == null)
                {
                    throw new ArgumentException("Domain not exists");
                }

                var aliasEmail = string.Format("{0}@{1}", alias.AddressName, serverDomain.Name);

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    serverAddressDao.Delete(addressId);
                    engine.RemoveAlias(aliasEmail);

                    tx.Commit();
                }

                CacheEngine.Clear(mailbox.User);
            }
        }
Esempio n. 8
0
        public ServerDomainAddressData AddAlias(int mailboxId, string aliasName)
        {
            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (string.IsNullOrEmpty(aliasName))
            {
                throw new ArgumentException(@"Invalid alias name.", "aliasName");
            }

            if (mailboxId < 0)
            {
                throw new ArgumentException(@"Invalid mailbox id.", "mailboxId");
            }

            if (aliasName.Length > 64)
            {
                throw new ArgumentException(@"Local part of mailbox alias exceed limitation of 64 characters.", "aliasName");
            }

            if (!Parser.IsEmailLocalPartValid(aliasName))
            {
                throw new ArgumentException("Incorrect mailbox alias.");
            }

            var mailboxAliasName = aliasName.ToLowerInvariant();

            using (var daoFactory = new DaoFactory())
            {
                var mailboxDao = daoFactory.CreateMailboxDao();

                var mailbox = mailboxDao.GetMailBox(new ConcreteTenantMailboxExp(mailboxId, Tenant));

                if (mailbox == null)
                {
                    throw new ArgumentException("Mailbox not exists");
                }

                if (!mailbox.IsTeamlabMailbox)
                {
                    throw new ArgumentException("Invalid mailbox type");
                }

                if (mailbox.Tenant == Defines.SHARED_TENANT_ID)
                {
                    throw new InvalidOperationException("Adding mailbox alias is not allowed for shared domain.");
                }

                var mailAddress = new MailAddress(mailbox.Address);

                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
                var serverDomain    = serverDomainDao.GetDomains().FirstOrDefault(d => d.Name == mailAddress.Host);

                if (serverDomain == null)
                {
                    throw new ArgumentException("Domain not exists");
                }

                var mailboxAddress = mailAddress.Address;

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                if (serverAddressDao.IsAddressAlreadyRegistered(mailboxAliasName, serverDomain.Name))
                {
                    throw new DuplicateNameException("You want to create a mailbox with already existing address.");
                }

                var utcNow = DateTime.UtcNow;

                var address = new ServerAddress
                {
                    Id          = 0,
                    Tenant      = Tenant,
                    MailboxId   = mailbox.Id,
                    DomainId    = serverDomain.Id,
                    AddressName = mailboxAliasName,
                    IsAlias     = true,
                    IsMailGroup = false,
                    DateCreated = utcNow
                };

                var aliasEmail = string.Format("{0}@{1}", mailboxAliasName, serverDomain.Name);

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    address.Id = serverAddressDao.Save(address);

                    var serverAddress = new Alias
                    {
                        Name     = mailbox.Name,
                        Address  = aliasEmail,
                        GoTo     = mailboxAddress,
                        Domain   = serverDomain.Name,
                        IsActive = true,
                        IsGroup  = false,
                        Modified = utcNow,
                        Created  = utcNow
                    };

                    engine.SaveAlias(serverAddress);

                    tx.Commit();
                }

                CacheEngine.Clear(mailbox.User);

                return(new ServerDomainAddressData
                {
                    Id = address.Id,
                    DomainId = address.DomainId,
                    Email = aliasEmail
                });
            }
        }
Esempio n. 9
0
        public ServerMailboxData CreateMailbox(string name, string localPart, int domainId, string userId)
        {
            ServerMailboxData mailboxData;

            using (var daoFactory = new DaoFactory())
            {
                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);

                var serverDomain = serverDomainDao.GetDomain(domainId);

                var isSharedDomain = serverDomain.Tenant == Defines.SHARED_TENANT_ID;

                if (!IsAdmin && !isSharedDomain)
                {
                    throw new SecurityException("Need admin privileges.");
                }

                var tenantQuota = CoreContext.TenantManager.GetTenantQuota(Tenant);

                if (isSharedDomain &&
                    (tenantQuota.Trial ||
                     tenantQuota.Free))
                {
                    throw new SecurityException("Not available in unpaid version");
                }

                if (string.IsNullOrEmpty(localPart))
                {
                    throw new ArgumentException(@"Invalid local part.", "localPart");
                }

                if (domainId < 0)
                {
                    throw new ArgumentException(@"Invalid domain id.", "domainId");
                }

                if (name.Length > 255)
                {
                    throw new ArgumentException(@"Sender name exceed limitation of 64 characters.", "name");
                }

                Guid user;

                if (!Guid.TryParse(userId, out user))
                {
                    throw new ArgumentException(@"Invalid user id.", "userId");
                }

                if (isSharedDomain && !IsAdmin && user != SecurityContext.CurrentAccount.ID)
                {
                    throw new SecurityException(
                              "Creation of a shared mailbox is allowed only for the current account if user is not admin.");
                }

                var teamlabAccount = CoreContext.Authentication.GetAccountByID(user);

                if (teamlabAccount == null)
                {
                    throw new InvalidDataException("Unknown user.");
                }

                var userInfo = CoreContext.UserManager.GetUsers(user);

                if (userInfo.IsVisitor())
                {
                    throw new InvalidDataException("User is visitor.");
                }

                if (localPart.Length > 64)
                {
                    throw new ArgumentException(@"Local part of mailbox exceed limitation of 64 characters.",
                                                "localPart");
                }

                if (!Parser.IsEmailLocalPartValid(localPart))
                {
                    throw new ArgumentException("Incorrect local part of mailbox.");
                }

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                if (serverAddressDao.IsAddressAlreadyRegistered(localPart, serverDomain.Name))
                {
                    throw new DuplicateNameException("You want to create a mailbox with already existing address.");
                }

                if (Defines.ServerDomainMailboxPerUserLimit > 0)
                {
                    var engineFactory = new EngineFactory(Tenant, userId);

                    var accounts = engineFactory.AccountEngine.GetAccountInfoList();

                    var countDomainMailboxes =
                        accounts.Count(a =>
                                       a.IsTeamlabMailbox &&
                                       Parser.ParseAddress(a.Email)
                                       .Domain.Equals(serverDomain.Name, StringComparison.InvariantCultureIgnoreCase));

                    if (countDomainMailboxes >= Defines.ServerDomainMailboxPerUserLimit)
                    {
                        throw new ArgumentOutOfRangeException(
                                  string.Format("Count of user's mailboxes must be less or equal {0}.",
                                                Defines.ServerDomainMailboxPerUserLimit));
                    }
                }

                var serverDao = daoFactory.CreateServerDao();

                var server = serverDao.Get(Tenant);

                var mailboxLocalPart = localPart.ToLowerInvariant();

                var login = string.Format("{0}@{1}", mailboxLocalPart, serverDomain.Name);

                var password = PasswordGenerator.GenerateNewPassword(12);

                var utcNow = DateTime.UtcNow;

                var mailboxDao = daoFactory.CreateMailboxDao();

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    var mailbox = new Mailbox
                    {
                        Id               = 0,
                        Tenant           = Tenant,
                        User             = userId,
                        Name             = name,
                        Address          = login,
                        OAuthToken       = null,
                        OAuthType        = (int)AuthorizationServiceType.None,
                        ServerId         = server.ImapSettingsId,
                        Password         = password,
                        SmtpServerId     = server.SmtpSettingsId,
                        SmtpPassword     = password,
                        SizeLast         = 0,
                        MsgCountLast     = 0,
                        BeginDate        = Defines.MinBeginDate,
                        Imap             = true,
                        Enabled          = true,
                        IsTeamlabMailbox = true,
                        IsRemoved        = false,
                        DateCreated      = utcNow
                    };

                    mailbox.Id = mailboxDao.SaveMailBox(mailbox);

                    var address = new ServerAddress
                    {
                        Id          = 0,
                        Tenant      = Tenant,
                        MailboxId   = mailbox.Id,
                        DomainId    = serverDomain.Id,
                        AddressName = localPart,
                        IsAlias     = false,
                        IsMailGroup = false,
                        DateCreated = utcNow
                    };

                    address.Id = serverAddressDao.Save(address);

                    var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                    var maildir = PostfixMaildirUtil.GenerateMaildirPath(serverDomain.Name, localPart, utcNow);

                    var serverMailbox = new Server.Core.Entities.Mailbox
                    {
                        Name      = name,
                        Password  = password,
                        Login     = login,
                        LocalPart = localPart,
                        Domain    = serverDomain.Name,
                        Active    = true,
                        Quota     = 0,
                        Maldir    = maildir,
                        Modified  = utcNow,
                        Created   = utcNow,
                    };

                    var serverAddress = new Alias
                    {
                        Name     = name,
                        Address  = login,
                        GoTo     = login,
                        Domain   = serverDomain.Name,
                        IsActive = true,
                        IsGroup  = false,
                        Modified = utcNow,
                        Created  = utcNow
                    };

                    engine.SaveMailbox(serverMailbox, serverAddress);

                    tx.Commit();

                    CacheEngine.Clear(userId);

                    mailboxData = ToMailboxData(mailbox, ToServerDomainAddressData(address, login),
                                                new List <ServerDomainAddressData>());
                }
            }

            return(mailboxData);
        }
Esempio n. 10
0
        public ServerNotificationAddressData CreateNotificationAddress(string localPart, string password, int domainId)
        {
            if (!CoreContext.Configuration.Standalone)
            {
                throw new SecurityException("Only for standalone");
            }

            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (string.IsNullOrEmpty(localPart))
            {
                throw new ArgumentNullException("localPart", @"Invalid address username.");
            }

            localPart = localPart.ToLowerInvariant().Trim();

            if (localPart.Length > 64)
            {
                throw new ArgumentException(@"Local part of address exceed limitation of 64 characters.", "localPart");
            }

            if (!Parser.IsEmailLocalPartValid(localPart))
            {
                throw new ArgumentException(@"Incorrect address username.", "localPart");
            }

            var trimPwd = Parser.GetValidPassword(password);

            if (domainId < 0)
            {
                throw new ArgumentException(@"Invalid domain id.", "domainId");
            }

            var notificationAddressSettings = ServerNotificationAddressSettings.LoadForTenant(Tenant);

            if (!string.IsNullOrEmpty(notificationAddressSettings.NotificationAddress))
            {
                RemoveNotificationAddress(notificationAddressSettings.NotificationAddress);
            }

            var utcNow = DateTime.UtcNow;

            using (var daoFactory = new DaoFactory())
            {
                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
                var serverDomain    = serverDomainDao.GetDomain(domainId);

                if (localPart.Length + serverDomain.Name.Length > 318) // 318 because of @ sign
                {
                    throw new ArgumentException(@"Address of mailbox exceed limitation of 319 characters.", "localPart");
                }

                var login = string.Format("{0}@{1}", localPart, serverDomain.Name);

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                if (server == null)
                {
                    throw new ArgumentException("Server not configured");
                }

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                var maildir = PostfixMaildirUtil.GenerateMaildirPath(serverDomain.Name, localPart, utcNow);

                var serverMailbox = new Server.Core.Entities.Mailbox
                {
                    Name      = localPart,
                    Password  = trimPwd,
                    Login     = login,
                    LocalPart = localPart,
                    Domain    = serverDomain.Name,
                    Active    = true,
                    Quota     = 0,
                    Maldir    = maildir,
                    Modified  = utcNow,
                    Created   = utcNow,
                };

                var serverAddress = new Alias
                {
                    Name     = localPart,
                    Address  = login,
                    GoTo     = login,
                    Domain   = serverDomain.Name,
                    IsActive = true,
                    IsGroup  = false,
                    Modified = utcNow,
                    Created  = utcNow
                };

                engine.SaveMailbox(serverMailbox, serverAddress, false);

                notificationAddressSettings = new ServerNotificationAddressSettings {
                    NotificationAddress = login
                };

                notificationAddressSettings.SaveForTenant(Tenant);

                var mailboxServerDao = daoFactory.CreateMailboxServerDao();

                var smtpSettings = mailboxServerDao.GetServer(server.SmtpSettingsId);

                var address = new MailAddress(login);

                var notifyAddress = new ServerNotificationAddressData
                {
                    Email                  = address.ToString(),
                    SmtpPort               = smtpSettings.Port,
                    SmtpServer             = smtpSettings.Hostname,
                    SmtpAccount            = address.ToLogin(smtpSettings.Username),
                    SmptEncryptionType     = smtpSettings.SocketType,
                    SmtpAuth               = true,
                    SmtpAuthenticationType = smtpSettings.Authentication
                };

                return(notifyAddress);
            }
        }
Esempio n. 11
0
        protected override void Do()
        {
            try
            {
                SetProgress((int?)MailOperationRemoveDomainProgress.Init, "Setup tenant and user");

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                try
                {
                    SecurityContext.AuthenticateMe(CurrentUser);
                }
                catch
                {
                    // User was removed
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                }

                SetProgress((int?)MailOperationRemoveDomainProgress.RemoveFromDb, "Remove domain from Db");

                var tenant = CurrentTenant.TenantId;

                var mailboxes = new List <MailBoxData>();

                var engine = new EngineFactory(tenant);

                using (var db = new DbManager(Defines.CONNECTION_STRING_NAME, Defines.RemoveDomainTimeout))
                {
                    var daoFactory = new DaoFactory(db);

                    using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                    {
                        var serverGroupDao = daoFactory.CreateServerGroupDao(tenant);

                        var serverAddressDao = daoFactory.CreateServerAddressDao(tenant);

                        var groups = serverGroupDao.GetList(_domain.Id);

                        foreach (var serverGroup in groups)
                        {
                            serverAddressDao.DeleteAddressesFromMailGroup(serverGroup.Id);
                            serverAddressDao.Delete(serverGroup.AddressId);
                            serverGroupDao.Delete(serverGroup.Id);
                        }

                        var serverAddresses = serverAddressDao.GetDomainAddresses(_domain.Id);

                        var serverMailboxAddresses = serverAddresses.Where(a => a.MailboxId > -1 && !a.IsAlias);

                        foreach (var serverMailboxAddress in serverMailboxAddresses)
                        {
                            var mailbox =
                                engine.MailboxEngine.GetMailboxData(
                                    new ConcreteTenantServerMailboxExp(serverMailboxAddress.MailboxId, tenant, false));

                            if (mailbox == null)
                            {
                                continue;
                            }

                            mailboxes.Add(mailbox);

                            engine.MailboxEngine.RemoveMailBox(daoFactory, mailbox, false);
                        }

                        serverAddressDao.Delete(serverAddresses.Select(a => a.Id).ToList());

                        var serverDomainDao = daoFactory.CreateServerDomainDao(tenant);

                        serverDomainDao.Delete(_domain.Id);

                        var serverDao = daoFactory.CreateServerDao();
                        var server    = serverDao.Get(tenant);

                        var serverEngine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                        serverEngine.RemoveDomain(_domain.Name);

                        tx.Commit();
                    }
                }

                SetProgress((int?)MailOperationRemoveDomainProgress.ClearCache, "Clear accounts cache");

                CacheEngine.ClearAll();

                SetProgress((int?)MailOperationRemoveDomainProgress.RemoveIndex, "Remove Elastic Search index by messages");

                foreach (var mailbox in mailboxes)
                {
                    engine.IndexEngine.Remove(mailbox);
                }
            }
            catch (Exception e)
            {
                Logger.Error("Mail operation error -> Remove mailbox: {0}", e);
                Error = "InternalServerError";
            }
        }
        public ServerDomainGroupData CreateMailGroup(string name, int domainId, List <int> addressIds)
        {
            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(@"Invalid mailgroup name.", "name");
            }

            if (domainId < 0)
            {
                throw new ArgumentException(@"Invalid domain id.", "domainId");
            }

            if (name.Length > 64)
            {
                throw new ArgumentException(@"Local part of mailgroup exceed limitation of 64 characters.", "name");
            }

            if (!Parser.IsEmailLocalPartValid(name))
            {
                throw new ArgumentException(@"Incorrect group name.", "name");
            }

            if (!addressIds.Any())
            {
                throw new ArgumentException(@"Empty collection of address_ids.", "addressIds");
            }

            var mailgroupName = name.ToLowerInvariant();

            using (var daoFactory = new DaoFactory())
            {
                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);

                var serverDomain = serverDomainDao.GetDomain(domainId);

                if (serverDomain.Tenant == Defines.SHARED_TENANT_ID)
                {
                    throw new InvalidOperationException("Creating mail group is not allowed for shared domain.");
                }

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                if (serverAddressDao.IsAddressAlreadyRegistered(mailgroupName, serverDomain.Name))
                {
                    throw new DuplicateNameException("You want to create a group with already existing address.");
                }

                var utcNow = DateTime.UtcNow;

                var address = new ServerAddress
                {
                    Id          = 0,
                    Tenant      = Tenant,
                    MailboxId   = -1,
                    DomainId    = serverDomain.Id,
                    AddressName = mailgroupName,
                    IsAlias     = false,
                    IsMailGroup = true,
                    DateCreated = utcNow
                };

                var groupEmail = string.Format("{0}@{1}", mailgroupName, serverDomain.Name);

                var groupAddressData = ServerMailboxEngine.ToServerDomainAddressData(address, groupEmail);

                var newGroupMembers = serverAddressDao.GetList(addressIds);

                var newGroupMemberIds = newGroupMembers.ConvertAll(m => m.Id);

                var newGroupMemberDataList =
                    newGroupMembers.ConvertAll(m =>
                                               ServerMailboxEngine.ToServerDomainAddressData(m,
                                                                                             string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));

                var goTo = string.Join(",",
                                       newGroupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                var group = new ServerGroup
                {
                    Id          = 0,
                    Tenant      = Tenant,
                    Address     = groupEmail,
                    AddressId   = 0,
                    DateCreated = utcNow
                };

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    address.Id = serverAddressDao.Save(address);

                    group.AddressId = address.Id;

                    var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);

                    group.Id = serverGroupDao.Save(group);

                    serverAddressDao.AddAddressesToMailGroup(group.Id, newGroupMemberIds);

                    var serverAddress = new Alias
                    {
                        Name     = "",
                        Address  = groupEmail,
                        GoTo     = goTo,
                        Domain   = serverDomain.Name,
                        IsActive = true,
                        IsGroup  = true,
                        Modified = utcNow,
                        Created  = utcNow
                    };

                    engine.SaveAlias(serverAddress);

                    tx.Commit();
                }

                CacheEngine.ClearAll();

                return(ToServerDomainGroupData(group.Id, groupAddressData, newGroupMemberDataList));
            }
        }
        public void RemoveMailGroupMember(int mailgroupId, int addressId)
        {
            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (addressId < 0)
            {
                throw new ArgumentException(@"Invalid address id.", "addressId");
            }

            if (mailgroupId < 0)
            {
                throw new ArgumentException(@"Invalid mailgroup id.", "mailgroupId");
            }

            using (var daoFactory = new DaoFactory())
            {
                var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);

                var group = serverGroupDao.Get(mailgroupId);

                if (group == null)
                {
                    throw new Exception("Group not found");
                }

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                var groupMembers = serverAddressDao.GetGroupAddresses(mailgroupId);

                var removeMember = groupMembers.FirstOrDefault(a => a.Id == addressId);

                if (removeMember == null)
                {
                    throw new ArgumentException("Member not found");
                }

                groupMembers.Remove(removeMember);

                if (groupMembers.Count == 0)
                {
                    throw new Exception("Can't remove last member; Remove group.");
                }

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                var groupAddress = serverAddressDao.Get(group.AddressId);

                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);

                var serverDomain = serverDomainDao.GetDomain(groupAddress.DomainId);

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                var utcNow = DateTime.UtcNow;

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    serverAddressDao.DeleteAddressFromMailGroup(mailgroupId, addressId);

                    var goTo = string.Join(",",
                                           groupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));

                    var groupEmail = string.Format("{0}@{1}", groupAddress.AddressName, serverDomain.Name);

                    var serverAddress = new Alias
                    {
                        Name     = "",
                        Address  = groupEmail,
                        GoTo     = goTo,
                        Domain   = serverDomain.Name,
                        IsActive = true,
                        IsGroup  = true,
                        Modified = utcNow,
                        Created  = group.DateCreated
                    };

                    engine.SaveAlias(serverAddress);

                    tx.Commit();
                }
            }

            CacheEngine.ClearAll();
        }
        public ServerDomainGroupData AddMailGroupMember(int mailgroupId, int addressId)
        {
            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (addressId < 0)
            {
                throw new ArgumentException(@"Invalid address id.", "addressId");
            }

            if (mailgroupId < 0)
            {
                throw new ArgumentException(@"Invalid mailgroup id.", "mailgroupId");
            }

            using (var daoFactory = new DaoFactory())
            {
                var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);

                var group = serverGroupDao.Get(mailgroupId);

                if (group == null)
                {
                    throw new Exception("Group not found");
                }

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                var groupMembers = serverAddressDao.GetGroupAddresses(mailgroupId);

                if (groupMembers.Exists(a => a.Id == addressId))
                {
                    throw new DuplicateNameException("Member already exists");
                }

                var newMemberAddress = serverAddressDao.Get(addressId);

                if (newMemberAddress == null)
                {
                    throw new Exception("Member not found");
                }

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                var utcNow = DateTime.UtcNow;

                ServerAddress groupAddress;
                string        groupEmail;
                List <ServerDomainAddressData> newGroupMemberDataList;

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    serverAddressDao.AddAddressesToMailGroup(mailgroupId, new List <int> {
                        addressId
                    });

                    groupMembers.Add(newMemberAddress);

                    groupAddress = serverAddressDao.Get(group.AddressId);

                    var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);

                    var serverDomain = serverDomainDao.GetDomain(groupAddress.DomainId);

                    var goTo = string.Join(",",
                                           groupMembers.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));

                    groupEmail = string.Format("{0}@{1}", groupAddress.AddressName, serverDomain.Name);

                    newGroupMemberDataList =
                        groupMembers.ConvertAll(m =>
                                                ServerMailboxEngine.ToServerDomainAddressData(m,
                                                                                              string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));

                    var serverAddress = new Alias
                    {
                        Name     = "",
                        Address  = groupEmail,
                        GoTo     = goTo,
                        Domain   = serverDomain.Name,
                        IsActive = true,
                        IsGroup  = true,
                        Modified = utcNow,
                        Created  = utcNow
                    };

                    engine.SaveAlias(serverAddress);

                    tx.Commit();
                }

                var groupAddressData = ServerMailboxEngine.ToServerDomainAddressData(groupAddress, groupEmail);

                CacheEngine.ClearAll();

                return(ToServerDomainGroupData(group.Id, groupAddressData, newGroupMemberDataList));
            }
        }
Esempio n. 15
0
        public ServerDomainData AddDomain(string domain, int dnsId)
        {
            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (string.IsNullOrEmpty(domain))
            {
                throw new ArgumentException(@"Invalid domain name.", "domain");
            }

            if (domain.Length > 255)
            {
                throw new ArgumentException(@"Domain name exceed limitation of 255 characters.", "domain");
            }

            if (!Parser.IsDomainValid(domain))
            {
                throw new ArgumentException(@"Incorrect domain name.", "domain");
            }

            var domainName = domain.ToLowerInvariant();

            var engine = new EngineFactory(Tenant, User);

            var dnsLookup = new DnsLookup();

            using (var daoFactory = new DaoFactory())
            {
                var serverDao = daoFactory.CreateServerDao();

                var server = serverDao.Get(Tenant);

                var freeDns = engine.ServerEngine.GetOrCreateUnusedDnsData(daoFactory, server);

                if (freeDns.Id != dnsId)
                {
                    throw new InvalidDataException("This dkim public key is already in use. Please reopen wizard again.");
                }

                if (!CoreContext.Configuration.Standalone &&
                    !dnsLookup.IsDomainTxtRecordExists(domainName, freeDns.DomainCheckRecord.Value))
                {
                    throw new InvalidOperationException("txt record is not correct.");
                }

                var isVerified = freeDns.CheckDnsStatus(domainName);

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);

                    var utcNow = DateTime.UtcNow;

                    var mailServerEngine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                    var mailServerDomain = new Server.Core.Entities.Domain
                    {
                        Name        = domainName,
                        Active      = true,
                        Description = string.Format("Domain created in UtcTime: {0}, for tenant: {1}", utcNow, Tenant),
                        Created     = utcNow,
                        Modified    = utcNow
                    };

                    mailServerEngine.SaveDomain(mailServerDomain);

                    var serverDomain = new ServerDomain
                    {
                        Id          = 0,
                        Tenant      = Tenant,
                        Name        = domainName,
                        IsVerified  = isVerified,
                        DateAdded   = utcNow,
                        DateChecked = utcNow
                    };

                    serverDomain.Id = serverDomainDao.Save(serverDomain);

                    var serverDnsDao = daoFactory.CreateServerDnsDao(Tenant, User);
                    var serverDns    = serverDnsDao.GetById(freeDns.Id);

                    var mailServerDkim = new Server.Core.Entities.Dkim
                    {
                        DomainName = domainName,
                        Selector   = serverDns.DkimSelector,
                        PrivateKey = serverDns.DkimPrivateKey,
                        PublicKey  = serverDns.DkimPublicKey
                    };

                    mailServerEngine.SaveDkim(mailServerDkim);

                    serverDns.DomainId     = serverDomain.Id;
                    serverDns.TimeModified = utcNow;
                    serverDnsDao.Save(serverDns);

                    tx.Commit();

                    return(ToServerDomainData(serverDomain, freeDns));
                }
            }
        }