예제 #1
0
 public string Serialize()
 {
     return(string.Join("#",
                        string.IsNullOrEmpty(password) ? string.Empty : InstanceCrypto.Encrypt(password),
                        (int)Status,
                        NotifyUsers
                        ));
 }
예제 #2
0
        public IActionResult IsCaldavAuthenticated(UserPassword userPassword)
        {
            if (userPassword == null || string.IsNullOrEmpty(userPassword.User) || string.IsNullOrEmpty(userPassword.Password))
            {
                Log.Error("CalDav authenticated data is null");

                return(BadRequest(new
                {
                    value = "false",
                    error = "portalNameEmpty",
                    message = "Argument is required"
                }));
            }

            if (!GetUserData(userPassword.User, out var email, out var tenant, out var error))
            {
                return(BadRequest(error));
            }

            try
            {
                Log.Info(string.Format("Caldav auth user: {0}, tenant: {1}", email, tenant.TenantId));

                if (InstanceCrypto.Encrypt(email) == userPassword.Password)
                {
                    return(Ok(new
                    {
                        value = "true"
                    }));
                }

                var validationKey = EmailValidationKeyProvider.GetEmailKey(tenant.TenantId, email + userPassword.Password + ConfirmType.Auth);

                var authData = string.Format("userName={0}&password={1}&key={2}",
                                             HttpUtility.UrlEncode(email),
                                             HttpUtility.UrlEncode(userPassword.Password),
                                             HttpUtility.UrlEncode(validationKey));

                SendToApi(Request.Scheme, tenant, "authentication/login", null, WebRequestMethods.Http.Post, authData);

                return(Ok(new
                {
                    value = "true"
                }));
            }
            catch (Exception ex)
            {
                Log.Error("Caldav authenticated", ex);

                return(StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    value = "false",
                    message = ex.Message
                }));
            }
        }
예제 #3
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="clientScriptManager"></param>
 /// <param name="type">The type of the client script to register</param>
 /// <param name="resourseType"></param>
 /// <param name="jsObjectName"></param>
 public static void RegisterJavaScriptResource(this ClientScriptManager clientScriptManager, Type resourseType, String jsObjectName)
 {
     if (!clientScriptManager.IsStartupScriptRegistered(typeof(Page), jsObjectName))
     {
         var param         = string.Join("|", new[] { resourseType.AssemblyQualifiedName, jsObjectName, Thread.CurrentThread.CurrentCulture.Name });
         var queryString   = "?d=" + HttpUtility.UrlEncode(InstanceCrypto.Encrypt(param));
         var scriptContent = string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", String.Concat(VirtualPathUtility.ToAbsolute("~/JavaScriptResource.ashx"), queryString));
         clientScriptManager.RegisterStartupScript(typeof(Page), jsObjectName, scriptContent, false);
     }
 }
예제 #4
0
        public static string EncryptCookie(int tenant, Guid userid, string login, string password)
        {
            var s = string.Format("{0}${1}${2}${3}${4}",
                                  (login ?? string.Empty).ToLowerInvariant(),
                                  tenant,
                                  password,
                                  GetUserDepenencySalt(),
                                  userid.ToString("N"));

            return(InstanceCrypto.Encrypt(s));
        }
예제 #5
0
        public static string EncryptCookie(int tenant, Guid userid, string login, string password, int indexTenant, DateTime expires, int indexUser)
        {
            var s = string.Format("{0}${1}${2}${3}${4}${5}${6}${7}",
                                  (login ?? string.Empty).ToLowerInvariant(),
                                  tenant,
                                  password,
                                  GetUserDepenencySalt(),
                                  userid.ToString("N"),
                                  indexTenant,
                                  expires.ToString(DateTimeFormat, CultureInfo.InvariantCulture),
                                  indexUser);

            return(InstanceCrypto.Encrypt(s));
        }
        public static byte[] GetPasswordBytes(string password)
        {
            byte[] passwordBytes;

            try
            {
                passwordBytes = InstanceCrypto.Encrypt(new UnicodeEncoding().GetBytes(password));
            }
            catch (Exception)
            {
                passwordBytes = null;
            }

            return(passwordBytes);
        }
예제 #7
0
        public static string EncryptCookie(int tenant, Guid userid, int indexTenant, DateTime expires, int indexUser, int loginEventId)
        {
            var s = string.Format("{0}${1}${2}${3}${4}${5}${6}${7}${8}",
                                  string.Empty, //login
                                  tenant,
                                  string.Empty, // password
                                  GetUserDepenencySalt(),
                                  userid.ToString("N"),
                                  indexTenant,
                                  expires.ToString(DateTimeFormat, CultureInfo.InvariantCulture),
                                  indexUser,
                                  loginEventId != 0 ? loginEventId.ToString() : null);

            return(InstanceCrypto.Encrypt(s));
        }
        public void SetKeys(Guid userId, string keys)
        {
            if (string.IsNullOrEmpty(keys))
            {
                return;
            }

            var loginProfile = new LoginProfile(Signature, InstanceCrypto)
            {
                Provider = ProviderConstants.Encryption,
                Name     = InstanceCrypto.Encrypt(keys)
            };

            var linker = Snapshot.Get("webstudio");

            linker.AddLink(userId.ToString(), loginProfile);
        }
        public static void SetKeys(Guid userId, string keys)
        {
            if (string.IsNullOrEmpty(keys))
            {
                return;
            }

            var loginProfile = new LoginProfile
            {
                Provider = ProviderConstants.Encryption,
                Name     = InstanceCrypto.Encrypt(keys),
            };

            var linker = new AccountLinker("webstudio");

            linker.AddLink(userId.ToString(), loginProfile);
        }
예제 #10
0
        public static string GetInitiateUploadSessionUrl(object folderId, object fileId, string fileName, long contentLength)
        {
            var queryString = string.Format("?initiate=true&name={0}&fileSize={1}&tid={2}&userid={3}",
                                            fileName, contentLength, TenantProvider.CurrentTenantID,
                                            HttpUtility.UrlEncode(InstanceCrypto.Encrypt(SecurityContext.CurrentAccount.ID.ToString())));

            if (fileId != null)
            {
                queryString = queryString + "&fileid=" + fileId;
            }

            if (folderId != null)
            {
                queryString = queryString + "&folderid=" + folderId;
            }

            return(CommonLinkUtility.GetFullAbsolutePath(GetFileUploaderHandlerVirtualPath(contentLength > 0) + queryString));
        }
예제 #11
0
        public static string GetInitiateUploadSessionUrl(object folderId, object fileId, string fileName, long contentLength)
        {
            var queryString = string.Format("?initiate=true&{0}={1}&fileSize={2}&tid={3}&userid={4}&culture={5}",
                                            FileTitle,
                                            HttpUtility.UrlEncode(fileName),
                                            contentLength,
                                            TenantProvider.CurrentTenantID,
                                            HttpUtility.UrlEncode(InstanceCrypto.Encrypt(SecurityContext.CurrentAccount.ID.ToString())),
                                            Thread.CurrentThread.CurrentUICulture.Name);

            if (fileId != null)
            {
                queryString = queryString + "&" + FileId + "=" + HttpUtility.UrlEncode(fileId.ToString());
            }

            if (folderId != null)
            {
                queryString = queryString + "&" + FolderId + "=" + HttpUtility.UrlEncode(folderId.ToString());
            }

            return(CommonLinkUtility.GetFullAbsolutePath(GetFileUploaderHandlerVirtualPath() + queryString));
        }
예제 #12
0
        private string GetSiteUnsubscribeLink(NoticeMessage message, MailWhiteLabelSettings settings)
        {
            var mail = message.Recipient.Addresses.FirstOrDefault(r => r.Contains("@"));

            if (string.IsNullOrEmpty(mail))
            {
                return(string.Empty);
            }

            var format = CoreBaseSettings.CustomMode
                             ? "{0}/unsubscribe/{1}"
                             : "{0}/Unsubscribe.aspx?id={1}";

            var site = settings == null
                           ? MailWhiteLabelSettingsHelper.DefaultMailSiteUrl
                           : settings.SiteUrl;

            return(string.Format(format,
                                 site,
                                 WebEncoders.Base64UrlEncode(
                                     InstanceCrypto.Encrypt(
                                         Encoding.UTF8.GetBytes(mail.ToLowerInvariant())))));
        }
예제 #13
0
 internal string Transport()
 {
     return(HttpServerUtility.UrlTokenEncode(InstanceCrypto.Encrypt(Encoding.UTF8.GetBytes(ToSerializedString()))));
 }
예제 #14
0
 public string CreateHash(string s)
 {
     return(!string.IsNullOrEmpty(s) && s.StartsWith("S|") ? instanceCrypto.Encrypt(Crypto.GetV(s.Substring(2), 1, false)) : s);
 }
예제 #15
0
 public void SetEncryptedCode(InstanceCrypto InstanceCrypto, string code)
 {
     Code = InstanceCrypto.Encrypt(code);
 }
예제 #16
0
        public MailboxWithAddressDto CreateMailbox(IAccount teamlabAccount, string name,
                                                   string fullAddress, string password, string addressName,
                                                   DateTime addressCreatedDate,
                                                   int domainId, string domainName, bool isVerified, DbManager db)
        {
            if (teamlabAccount == null)
            {
                throw new ArgumentNullException("teamlabAccount");
            }

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

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

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

            if (domainId < 0)
            {
                throw new ArgumentException("Argument domain_id less then zero.", "domainId");
            }

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

            if (db == null)
            {
                throw new ArgumentNullException("db");
            }

            const string mailbox_alias = "mb";
            const string address_alias = "a";

            var userTeamlabMailboxCountQuery = new SqlQuery(MailboxTable.Name.Alias(mailbox_alias))
                                               .InnerJoin(AddressTable.Name.Alias(address_alias),
                                                          Exp.EqColumns(MailboxTable.Columns.Id.Prefix(mailbox_alias),
                                                                        AddressTable.Columns.MailboxId.Prefix(address_alias)))
                                               .SelectCount()
                                               .Where(MailboxTable.Columns.IsTeamlabMailbox.Prefix(mailbox_alias), true)
                                               .Where(MailboxTable.Columns.IsRemoved.Prefix(mailbox_alias), false)
                                               .Where(MailboxTable.Columns.Tenant.Prefix(mailbox_alias), tenant)
                                               .Where(MailboxTable.Columns.User.Prefix(mailbox_alias), teamlabAccount.ID.ToString())
                                               .Where(AddressTable.Columns.DomainId.Prefix(address_alias), domainId)
                                               .Where(AddressTable.Columns.IsAlias.Prefix(address_alias), false);

            var userMailboxesCount = db.ExecuteScalar <int>(userTeamlabMailboxCountQuery);

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

            var serverInformation = GetTenantServer(db);

            var dateCreated = DateTime.UtcNow;

            var insertQuery = new SqlInsert(MailboxTable.Name)
                              .InColumnValue(MailboxTable.Columns.Id, 0)
                              .InColumnValue(MailboxTable.Columns.Tenant, tenant)
                              .InColumnValue(MailboxTable.Columns.User, teamlabAccount.ID.ToString())
                              .InColumnValue(MailboxTable.Columns.Address, fullAddress)
                              .InColumnValue(MailboxTable.Columns.AddressName, name)
                              .InColumnValue(MailboxTable.Columns.Password, InstanceCrypto.Encrypt(password))
                              .InColumnValue(MailboxTable.Columns.MsgCountLast, 0)
                              .InColumnValue(MailboxTable.Columns.SmtpPassword, InstanceCrypto.Encrypt(password))
                              .InColumnValue(MailboxTable.Columns.SizeLast, 0)
                              .InColumnValue(MailboxTable.Columns.LoginDelay, Config.LoginDelayInSeconds)
                              .InColumnValue(MailboxTable.Columns.Enabled, true)
                              .InColumnValue(MailboxTable.Columns.Imap, true)
                              .InColumnValue(MailboxTable.Columns.OAuthType, AuthorizationServiceType.None)
                              .InColumnValue(MailboxTable.Columns.OAuthToken, null)
                              .InColumnValue(MailboxTable.Columns.DateCreated, dateCreated)
                              .InColumnValue(MailboxTable.Columns.SmtpServerId, serverInformation.smtp_settings_id)
                              .InColumnValue(MailboxTable.Columns.ServerId, serverInformation.imap_settings_id)
                              .InColumnValue(MailboxTable.Columns.IsTeamlabMailbox, true)
                              .Identity(0, 0, true);


            var result = db.ExecuteScalar <int>(insertQuery);

            var createdMailbox = new MailboxDto(result, teamlabAccount.ID.ToString(), tenant,
                                                fullAddress, name);

            var addressDal = new MailAddressDal(tenant);

            var mailboxAddress = addressDal.AddMailboxAddress(createdMailbox.id, addressName, addressCreatedDate,
                                                              domainId, domainName, isVerified, db);

            var resultDto = new MailboxWithAddressDto(createdMailbox, mailboxAddress);

            return(resultDto);
        }
예제 #17
0
 private string EncryptPassword(string password)
 {
     return(InstanceCrypto.Encrypt(password));
 }
예제 #18
0
        private void PrepareSettings(LDAPSupportSettings settings)
        {
            if (settings == null)
            {
                Logger.Error("Wrong LDAP settings were received from client.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (!settings.EnableLdapAuthentication)
            {
                settings.Password = string.Empty;
                return;
            }

            if (!string.IsNullOrWhiteSpace(settings.Server))
            {
                settings.Server = settings.Server.Trim();
            }
            else
            {
                Logger.Error("settings.Server is null or empty.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (!settings.Server.StartsWith("LDAP://"))
            {
                settings.Server = "LDAP://" + settings.Server;
            }

            if (!string.IsNullOrWhiteSpace(settings.UserDN))
            {
                settings.UserDN = settings.UserDN.Trim();
            }
            else
            {
                Logger.Error("settings.UserDN is null or empty.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (!string.IsNullOrWhiteSpace(settings.LoginAttribute))
            {
                settings.LoginAttribute = settings.LoginAttribute.Trim();
            }
            else
            {
                Logger.Error("settings.LoginAttribute is null or empty.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (!string.IsNullOrWhiteSpace(settings.UserFilter))
            {
                settings.UserFilter = settings.UserFilter.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.FirstNameAttribute))
            {
                settings.FirstNameAttribute = settings.FirstNameAttribute.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.SecondNameAttribute))
            {
                settings.SecondNameAttribute = settings.SecondNameAttribute.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.MailAttribute))
            {
                settings.MailAttribute = settings.MailAttribute.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.TitleAttribute))
            {
                settings.TitleAttribute = settings.TitleAttribute.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.MobilePhoneAttribute))
            {
                settings.MobilePhoneAttribute = settings.MobilePhoneAttribute.Trim();
            }

            if (settings.GroupMembership)
            {
                if (!string.IsNullOrWhiteSpace(settings.GroupDN))
                {
                    settings.GroupDN = settings.GroupDN.Trim();
                }
                else
                {
                    Logger.Error("settings.GroupDN is null or empty.");
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    return;
                }

                if (!string.IsNullOrWhiteSpace(settings.GroupFilter))
                {
                    settings.GroupFilter = settings.GroupFilter.Trim();
                }

                if (!string.IsNullOrWhiteSpace(settings.GroupAttribute))
                {
                    settings.GroupAttribute = settings.GroupAttribute.Trim();
                }
                else
                {
                    Logger.Error("settings.GroupAttribute is null or empty.");
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    return;
                }

                if (!string.IsNullOrWhiteSpace(settings.UserAttribute))
                {
                    settings.UserAttribute = settings.UserAttribute.Trim();
                }
                else
                {
                    Logger.Error("settings.UserAttribute is null or empty.");
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    return;
                }
            }

            if (WorkContext.IsMono)
            {
                settings.Authentication = true;
            }

            if (!settings.Authentication)
            {
                settings.Password = string.Empty;
                return;
            }

            if (!string.IsNullOrWhiteSpace(settings.Login))
            {
                settings.Login = settings.Login.Trim();
            }
            else
            {
                Logger.Error("settings.Login is null or empty.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (settings.PasswordBytes == null || !settings.PasswordBytes.Any())
            {
                if (!string.IsNullOrEmpty(settings.Password))
                {
                    settings.PasswordBytes =
                        InstanceCrypto.Encrypt(new UnicodeEncoding().GetBytes(settings.Password));
                }
                else
                {
                    Logger.Error("settings.Password is null or empty.");
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    return;
                }
            }

            settings.Password = string.Empty;
        }
예제 #19
0
        public MailboxWithAddressDto CreateMailbox(IAccount teamlab_account,
                                                   string full_address, string password, string address_name,
                                                   DateTime address_created_date,
                                                   int domain_id, string domain_name, bool is_verified, DbManager db)
        {
            if (teamlab_account == null)
            {
                throw new ArgumentNullException("teamlab_account");
            }

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

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

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

            if (domain_id < 0)
            {
                throw new ArgumentException("Argument domain_id less then zero.", "domain_id");
            }

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

            if (db == null)
            {
                throw new ArgumentNullException("db");
            }

            const string mailbox_alias = "mb";
            const string address_alias = "a";

            var user_teamlab_mailbox_count_query = new SqlQuery(MailboxTable.name.Alias(mailbox_alias))
                                                   .InnerJoin(AddressTable.name.Alias(address_alias),
                                                              Exp.EqColumns(MailboxTable.Columns.id.Prefix(mailbox_alias),
                                                                            AddressTable.Columns.id_mailbox.Prefix(address_alias)))
                                                   .SelectCount()
                                                   .Where(MailboxTable.Columns.is_teamlab_mailbox.Prefix(mailbox_alias), true)
                                                   .Where(MailboxTable.Columns.is_removed.Prefix(mailbox_alias), false)
                                                   .Where(MailboxTable.Columns.id_tenant.Prefix(mailbox_alias), tenant_id)
                                                   .Where(MailboxTable.Columns.id_user.Prefix(mailbox_alias), teamlab_account.ID.ToString())
                                                   .Where(AddressTable.Columns.id_domain.Prefix(address_alias), domain_id)
                                                   .Where(AddressTable.Columns.is_alias.Prefix(address_alias), false);

            var user_mailboxes_count = db.ExecuteScalar <int>(user_teamlab_mailbox_count_query);

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

            var server_information = GetTenantServer(db);

            var date_created = DateTime.UtcNow.ToDbStyle();

            var insert_query = new SqlInsert(MailboxTable.name)
                               .InColumnValue(MailboxTable.Columns.id, 0)
                               .InColumnValue(MailboxTable.Columns.id_tenant, tenant_id)
                               .InColumnValue(MailboxTable.Columns.id_user, teamlab_account.ID.ToString())
                               .InColumnValue(MailboxTable.Columns.address, full_address) //Todo: Talk with AK about this.
                               .InColumnValue(MailboxTable.Columns.name, teamlab_account.Name)
                               .InColumnValue(MailboxTable.Columns.password, InstanceCrypto.Encrypt(password))
                               .InColumnValue(MailboxTable.Columns.msg_count_last, 0)
                               .InColumnValue(MailboxTable.Columns.smtp_password, InstanceCrypto.Encrypt(password))
                               .InColumnValue(MailboxTable.Columns.size_last, 0)
                               .InColumnValue(MailboxTable.Columns.login_delay, Config.LoginDelayInSeconds)
                               .InColumnValue(MailboxTable.Columns.enabled, true)
                               .InColumnValue(MailboxTable.Columns.imap, true)
                               .InColumnValue(MailboxTable.Columns.service_type, 0)
                               .InColumnValue(MailboxTable.Columns.refresh_token, null)
                               .InColumnValue(MailboxTable.Columns.date_created, date_created)
                               .InColumnValue(MailboxTable.Columns.id_smtp_server, server_information.smtp_settings_id)
                               .InColumnValue(MailboxTable.Columns.id_in_server, server_information.imap_settings_id)
                               .InColumnValue(MailboxTable.Columns.is_teamlab_mailbox, true)
                               .Identity(0, 0, true);


            var result = db.ExecuteScalar <int>(insert_query);

            var created_mailbox = new MailboxDto(result, teamlab_account.ID.ToString(), tenant_id,
                                                 full_address);

            var address_dal = new MailAddressDal(tenant_id);

            var mailbox_address = address_dal.AddMailboxAddress(created_mailbox.id, address_name, address_created_date,
                                                                domain_id, domain_name, is_verified, db);

            var result_dto = new MailboxWithAddressDto(created_mailbox, mailbox_address);

            return(result_dto);
        }
예제 #20
0
        protected override void Do()
        {
            List <File>   filesForSend;
            List <Folder> folderForSend;

            var entriesPathId = GetEntriesPathId(out filesForSend, out folderForSend);

            if (entriesPathId == null || entriesPathId.Count == 0)
            {
                if (0 < Files.Count)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
            }

            Total = entriesPathId.Count + 1;

            ReplaceLongPath(entriesPathId);

            using (var stream = CompressTo(entriesPathId))
            {
                if (stream != null)
                {
                    stream.Position = 0;

                    string fileName;

                    if (Folders.Count == 1 && Files.Count == 0)
                    {
                        fileName = String.Format(@"{0}{1}", FolderDao.GetFolder(Folders[0]).Title, CompressToArchive.Instance.ArchiveExtension);
                    }
                    else
                    {
                        fileName = String.Format(@"{0}-{1}-{2}{3}", CoreContext.TenantManager.GetCurrentTenant().TenantAlias.ToLower(), FileConstant.DownloadTitle, DateTime.UtcNow.ToString("yyyy-MM-dd"), CompressToArchive.Instance.ArchiveExtension);
                    }

                    var store = Global.GetStore();

                    var path = string.Format(@"{0}\{1}", ((IAccount)Thread.CurrentPrincipal.Identity).ID, fileName);

                    if (store.IsFile(FileConstant.StorageDomainTmp, path))
                    {
                        store.Delete(FileConstant.StorageDomainTmp, path);
                    }

                    store.Save(
                        FileConstant.StorageDomainTmp,
                        path,
                        stream,
                        MimeMapping.GetMimeMapping(path),
                        "attachment; filename=\"" + Uri.EscapeDataString(fileName) + "\"");

                    Status = string.Format("{0}?{1}=bulk&filename={2}", FilesLinkUtility.FileHandlerPath, FilesLinkUtility.Action, Uri.EscapeDataString(InstanceCrypto.Encrypt(fileName)));

                    ProgressStep();
                }
            }

            foreach (var file in filesForSend)
            {
                var key = file.ID.ToString();
                if (files.ContainsKey(key) && !string.IsNullOrEmpty(files[key]))
                {
                    FilesMessageService.Send(file, headers, MessageAction.FileDownloadedAs, file.Title, files[key]);
                }
                else
                {
                    FilesMessageService.Send(file, headers, MessageAction.FileDownloaded, file.Title);
                }
            }

            foreach (var folder in folderForSend)
            {
                FilesMessageService.Send(folder, headers, MessageAction.FolderDownloaded, folder.Title);
            }
        }
예제 #21
0
            public void RunJob()
            {
                Percentage = 1;
                Status     = Resource.LdapSettingsStatusCheckingLdapSettings;
                var tenantID = (int)Id;

                CoreContext.TenantManager.SetCurrentTenant(tenantID);
                if (_serializeSettings == null)
                {
                    _log.ErrorFormat("Can't save default LDAP settings.");
                    Error       = Resource.LdapSettingsErrorCantGetLdapSettings;
                    IsCompleted = true;
                    return;
                }
                try
                {
                    var settings = (LDAPSupportSettings)JavaScriptDeserializer.DeserializeFromJson(_serializeSettings, typeof(LDAPSupportSettings));
                    if (settings == null)
                    {
                        _log.ErrorFormat("Wrong LDAP settings were received from client.");
                        Error       = Resource.LdapSettingsErrorCantGetLdapSettings;
                        IsCompleted = true;
                        return;
                    }
                    if (!settings.Server.StartsWith("LDAP://"))
                    {
                        settings.Server = "LDAP://" + settings.Server;
                    }
                    if (!string.IsNullOrEmpty(settings.Password))
                    {
                        settings.PasswordBytes = InstanceCrypto.Encrypt(new UnicodeEncoding().GetBytes(settings.Password));
                    }
                    settings.Password = string.Empty;
                    var error = GetError(ADDomain.CheckSettings(settings, _importer));
                    if (error == string.Empty)
                    {
                        Status     = Resource.LdapSettingsStatusSavingSettings;
                        Percentage = 3;
                        if (!SettingsManager.Instance.SaveSettings <LDAPSupportSettings>(settings, tenantID))
                        {
                            _log.ErrorFormat("Can't save LDAP settings.");
                            Error       = Resource.LdapSettingsErrorCantSaveLdapSettings;
                            IsCompleted = true;
                            return;
                        }
                        // for logout old ldap users
                        AddLToSids();

                        if (settings.EnableLdapAuthentication)
                        {
                            CreateUsersAndGroups(settings);
                        }
                        Percentage = 100;
                    }
                    else
                    {
                        Error = error;
                    }
                }
                catch (TenantQuotaException e)
                {
                    _log.ErrorFormat("TenantQuotaException.", e);
                    Error = Resource.LdapSettingsTenantQuotaSettled;
                }
                catch (FormatException)
                {
                    Error = Resource.LdapSettingsErrorCantCreateUsers;
                }
                catch (Exception e)
                {
                    _log.ErrorFormat("Internal server error.", e);
                    Error = Resource.LdapSettingsInternalServerError;
                }
                IsCompleted = true;
            }
예제 #22
0
 public string GetSystemAuthorization()
 {
     return(ConfigurationManagerExtension.AppSettings["radicale.admin.data"] + ":" + InstanceCrypto.Encrypt(ConfigurationManagerExtension.AppSettings["radicale.admin.data"]));
 }
예제 #23
0
 private static string EncryptPassword(string password)
 {
     return(string.IsNullOrEmpty(password) ? string.Empty : InstanceCrypto.Encrypt(password));
 }
예제 #24
0
        public void DeleteUser(Guid id)
        {
            if (IsSystemUser(id))
            {
                return;
            }
            SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser);
            if (id == CoreContext.TenantManager.GetCurrentTenant().OwnerId)
            {
                throw new InvalidOperationException("Can not remove tenant owner.");
            }

            var delUser = CoreContext.UserManager.GetUsers(id);

            userService.RemoveUser(CoreContext.TenantManager.GetCurrentTenant().TenantId, id);
            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            try
            {
                var curreMail           = delUser.Email.ToLower();
                var currentAccountPaswd = InstanceCrypto.Encrypt(curreMail);
                var userAuthorization   = curreMail + ":" + currentAccountPaswd;
                var cardDavAddBook      = new CardDavAddressbook();
                var rootAuthorization   = cardDavAddBook.GetSystemAuthorization();
                var myUri = (HttpContext.Current != null) ? HttpContext.Current.Request.GetUrlRewriter().ToString() :
                            (Cache.Get <string>("REWRITE_URL" + tenant.TenantId) != null) ?
                            new Uri(Cache.Get <string>("REWRITE_URL" + tenant.TenantId)).ToString() : tenant.GetTenantDomain();
                var davUsersEmails    = CoreContext.UserManager.GetDavUserEmails();
                var requestUrlBook    = cardDavAddBook.GetRadicaleUrl(myUri, delUser.Email.ToLower(), true, true);
                var addBookCollection = cardDavAddBook.GetCollection(requestUrlBook, userAuthorization, myUri.ToString()).Result;


                if (addBookCollection.Completed && addBookCollection.StatusCode != 404)
                {
                    var davbookRequest = new DavRequest()
                    {
                        Url           = requestUrlBook,
                        Authorization = rootAuthorization,
                        Header        = myUri
                    };
                    RadicaleClient.RemoveAsync(davbookRequest).ConfigureAwait(false);
                }

                foreach (string email in davUsersEmails)
                {
                    var requestUrlItem = cardDavAddBook.GetRadicaleUrl(myUri.ToString(), email.ToLower(), true, true, itemID: delUser.ID.ToString());
                    try
                    {
                        var davItemRequest = new DavRequest()
                        {
                            Url           = requestUrlItem,
                            Authorization = rootAuthorization,
                            Header        = myUri
                        };
                        RadicaleClient.RemoveAsync(davItemRequest).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        LogManager.GetLogger("ASC").Error("ERROR: " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("ASC").Error("ERROR: " + ex.Message);
            }
        }
예제 #25
0
        private static string EncryptToken(OAuth20Token token)
        {
            var t = token.ToJson();

            return(string.IsNullOrEmpty(t) ? string.Empty : InstanceCrypto.Encrypt(t));
        }
예제 #26
0
        public UserInfo SaveUserInfo(UserInfo u, bool isVisitor = false, bool syncCardDav = false)
        {
            if (IsSystemUser(u.ID))
            {
                return(systemUsers[u.ID]);
            }
            if (u.ID == Guid.Empty)
            {
                SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser);
            }
            else
            {
                SecurityContext.DemandPermissions(new UserSecurityProvider(u.ID), Constants.Action_EditUser);
            }

            if (!CoreContext.Configuration.Personal)
            {
                if (Constants.MaxEveryoneCount <= GetUsersByGroup(Constants.GroupEveryone.ID).Length)
                {
                    throw new TenantQuotaException("Maximum number of users exceeded");
                }

                if (u.Status == EmployeeStatus.Active)
                {
                    if (isVisitor)
                    {
                        var maxUsers = CoreContext.TenantManager.GetTenantQuota(CoreContext.TenantManager.GetCurrentTenant().TenantId).ActiveUsers;

                        if (!CoreContext.Configuration.Standalone && CoreContext.UserManager.GetUsersByGroup(Constants.GroupVisitor.ID).Length > Constants.CoefficientOfVisitors * maxUsers)
                        {
                            throw new TenantQuotaException("Maximum number of visitors exceeded");
                        }
                    }
                    else
                    {
                        var q = CoreContext.TenantManager.GetTenantQuota(CoreContext.TenantManager.GetCurrentTenant().TenantId);
                        if (q.ActiveUsers < GetUsersByGroup(Constants.GroupUser.ID).Length)
                        {
                            throw new TenantQuotaException(string.Format("Exceeds the maximum active users ({0})", q.ActiveUsers));
                        }
                    }
                }
            }

            if (u.Status == EmployeeStatus.Terminated && u.ID == CoreContext.TenantManager.GetCurrentTenant().OwnerId)
            {
                throw new InvalidOperationException("Can not disable tenant owner.");
            }

            var oldUserData = userService.GetUserByUserName(CoreContext.TenantManager.GetCurrentTenant().TenantId, u.UserName);
            var newUser     = userService.SaveUser(CoreContext.TenantManager.GetCurrentTenant().TenantId, u);

            if (syncCardDav)
            {
                var tenant    = CoreContext.TenantManager.GetCurrentTenant();
                var cardDavAB = new CardDavAddressbook();
                var myUri     = (HttpContext.Current != null) ? HttpContext.Current.Request.GetUrlRewriter().ToString() :
                                (Cache.Get <string>("REWRITE_URL" + tenant.TenantId) != null) ?
                                new Uri(Cache.Get <string>("REWRITE_URL" + tenant.TenantId)).ToString() : tenant.GetTenantDomain();

                var rootAuthorization = cardDavAB.GetSystemAuthorization();
                var allUserEmails     = CoreContext.UserManager.GetDavUserEmails().ToList();
                var cardDavAddBook    = new CardDavAddressbook();

                if (oldUserData != null && oldUserData.Status != newUser.Status && newUser.Status == EmployeeStatus.Terminated)
                {
                    var userAuthorization = oldUserData.Email.ToLower() + ":" + InstanceCrypto.Encrypt(oldUserData.Email);
                    var requestUrlBook    = cardDavAB.GetRadicaleUrl(myUri, newUser.Email.ToLower(), true, true);
                    var collection        = cardDavAB.GetCollection(requestUrlBook, userAuthorization, myUri.ToString()).Result;
                    if (collection.Completed && collection.StatusCode != 404)
                    {
                        cardDavAB.Delete(myUri, newUser.ID, newUser.Email, tenant.TenantId);
                    }
                    foreach (string email in allUserEmails)
                    {
                        var requestUrlItem = cardDavAddBook.GetRadicaleUrl(myUri.ToString(), email.ToLower(), true, true, itemID: newUser.ID.ToString());
                        try
                        {
                            var davItemRequest = new DavRequest()
                            {
                                Url           = requestUrlItem,
                                Authorization = rootAuthorization,
                                Header        = myUri
                            };
                            RadicaleClient.RemoveAsync(davItemRequest).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetLogger("ASC").Error("ERROR: " + ex.Message);
                        }
                    }
                }
                else
                {
                    try
                    {
                        var cardDavUser = new CardDavItem(u.ID, u.FirstName, u.LastName, u.UserName, u.BirthDate, u.Sex, u.Title, u.Email, u.Contacts, u.MobilePhone);

                        try
                        {
                            cardDavAB.UpdateItemForAllAddBooks(allUserEmails, myUri, cardDavUser, CoreContext.TenantManager.GetCurrentTenant().TenantId, oldUserData != null && oldUserData.Email != newUser.Email ? oldUserData.Email : null);
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetLogger("ASC").Error("ERROR: " + ex.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.GetLogger("ASC").Error("ERROR: " + ex.Message);
                    }
                }
            }


            return(newUser);
        }
예제 #27
0
        public SaveSettingsResult SaveSettings(string serializeSettings)
        {
            CheckSsoPermissions();

            var saveSettingsResult = new SaveSettingsResult();

            var log = LogManager.GetLogger(typeof(SettingsApi));

            try
            {
                if (string.IsNullOrWhiteSpace(serializeSettings))
                {
                    log.Error("SSO settings are null or empty.");
                    saveSettingsResult.Status = Resource.SsoSettingsAreEmpty;
                    return(saveSettingsResult);
                }

                var settings = JsonConvert.DeserializeObject <SsoSettings>(serializeSettings);
                if (settings == null)
                {
                    log.Error("Wrong SSO settings were received from client.");
                    saveSettingsResult.Status = Resource.SsoSettingsWrongSerialization;
                    return(saveSettingsResult);
                }

                if (settings.EnableSso)
                {
                    if (!(string.IsNullOrWhiteSpace(settings.Issuer) || CheckUri(settings.Issuer)))
                    {
                        log.ErrorFormat("Wrong Issuer URL: {0}", settings.Issuer);
                        saveSettingsResult.Status = string.Format(Resource.SsoSettingsWrongURL, settings.Issuer);
                        return(saveSettingsResult);
                    }
                    settings.Issuer = settings.Issuer.Trim();

                    if (!(string.IsNullOrWhiteSpace(settings.SsoEndPoint) || CheckUri(settings.SsoEndPoint)))
                    {
                        log.ErrorFormat("Wrong SsoEndPoint URL: {0}", settings.SsoEndPoint);
                        saveSettingsResult.Status = string.Format(Resource.SsoSettingsWrongURL, settings.SsoEndPoint);
                        return(saveSettingsResult);
                    }

                    settings.SsoEndPoint = settings.SsoEndPoint.Trim();

                    if (!string.IsNullOrWhiteSpace(settings.SloEndPoint) && !CheckUri(settings.SloEndPoint))
                    {
                        log.ErrorFormat("Wrong SloEndPoint URL: {0}", settings.SloEndPoint);
                        saveSettingsResult.Status = string.Format(Resource.SsoSettingsWrongURL, settings.SloEndPoint);
                        return(saveSettingsResult);
                    }

                    settings.SloEndPoint = (settings.SloEndPoint ?? "").Trim();

                    if (string.IsNullOrWhiteSpace(settings.PublicKey))
                    {
                        log.ErrorFormat("Wrong PublicKey: {0}", settings.PublicKey);
                        saveSettingsResult.Status = Resource.SsoSettingsWrongPublicKey;
                        return(saveSettingsResult);
                    }

                    settings.PublicKey = settings.PublicKey.Trim();

                    if (settings.TokenType != TokenTypes.SAML && settings.TokenType != TokenTypes.JWT)
                    {
                        log.ErrorFormat("Wrong token type: {0}", settings.TokenType);
                        saveSettingsResult.Status = Resource.SsoSettingsWrongTokenType;
                        return(saveSettingsResult);
                    }

                    if (settings.ValidationType != ValidationTypes.HMAC_SHA256 &&
                        settings.ValidationType != ValidationTypes.RSA_SHA256 &&
                        settings.ValidationType != ValidationTypes.X509)
                    {
                        log.ErrorFormat("Wrong validaion type: {0}", settings.ValidationType);
                        saveSettingsResult.Status = Resource.SsoSettingsWrongValidationType;
                        return(saveSettingsResult);
                    }

                    //TODO: Why is it necessary?
                    if (settings.TokenType == TokenTypes.SAML && settings.ValidationType != ValidationTypes.X509)
                    {
                        settings.ValidationType = ValidationTypes.X509;
                    }
                }

                var base64ExportCertificate = FillBase64ExportCertificate(settings, log);

                if (!string.IsNullOrEmpty(settings.ClientCertificateFileName) && string.IsNullOrEmpty(base64ExportCertificate))
                {
                    log.ErrorFormat("Wrong certificate or password: {0}", settings.ClientCertificateFileName);
                    saveSettingsResult.Status = Resource.WrongPasswordOrIncorrectCertitificate;
                    return(saveSettingsResult);
                }

                if (!string.IsNullOrEmpty(settings.ClientPassword))
                {
                    settings.ClientPassword = InstanceCrypto.Encrypt(settings.ClientPassword);
                }

                if (!settings.Save())
                {
                    log.Error("Can't save SSO settings.");
                    saveSettingsResult.Status = Resource.SsoSettingsCantSaveSettings;
                    return(saveSettingsResult);
                }

                var messageAction = settings.EnableSso ? MessageAction.SSOEnabled : MessageAction.SSODisabled;

                MessageService.Send(HttpContext.Current.Request, messageAction);

                saveSettingsResult.PublicKey = base64ExportCertificate;
                saveSettingsResult.Status    = string.Empty;
            }
            catch (Exception e)
            {
                log.ErrorFormat("Save SSO setting, error: {0}", e);
                saveSettingsResult.Status = Resource.SsoSettingsUnexpectedError;
            }

            return(saveSettingsResult);
        }
예제 #28
0
 internal string Transport()
 {
     return(WebEncoders.Base64UrlEncode(InstanceCrypto.Encrypt(Encoding.UTF8.GetBytes(ToSerializedString()))));
 }
예제 #29
0
 public static string EncryptPassword(string password)
 {
     return(InstanceCrypto.Encrypt(password));
 }
예제 #30
0
        public async Task <DavResponse> GetCardDavUrl()
        {
            if (WebItemManager.Instance[WebItemManager.PeopleProductID].IsDisabled())
            {
                await DeleteCardDavAddressBook().ConfigureAwait(false);

                throw new MethodAccessException("Method not available");
            }

            var myUri               = HttpContext.Current.Request.GetUrlRewriter();
            var currUser            = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            var userName            = currUser.Email.ToLower();
            var currentAccountPaswd = InstanceCrypto.Encrypt(userName);
            var cardBuilder         = CardDavAllSerialization(myUri);


            var cardDavAddBook    = new CardDavAddressbook();
            var userAuthorization = userName + ":" + currentAccountPaswd;
            var rootAuthorization = cardDavAddBook.GetSystemAuthorization();
            var sharedCardUrl     = cardDavAddBook.GetRadicaleUrl(myUri.ToString(), userName, true, true, true);
            var getResponse       = cardDavAddBook.GetCollection(sharedCardUrl, userAuthorization, myUri.ToString()).Result;

            if (getResponse.Completed)
            {
                return(new DavResponse()
                {
                    Completed = true,
                    Data = sharedCardUrl
                });
            }
            else if (getResponse.StatusCode == 404)
            {
                var cardAB         = new CardDavAddressbook();
                var createResponse = cardAB.Create("", "", "", sharedCardUrl, rootAuthorization).Result;
                if (createResponse.Completed)
                {
                    try
                    {
                        var dbConn = new DbRadicale();
                        dbConn.SaveCardDavUser(CurrentTenant, currUser.ID.ToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Error("ERROR: " + ex.Message);
                    }

                    await cardAB.UpdateItem(sharedCardUrl, rootAuthorization, cardBuilder, myUri.ToString()).ConfigureAwait(false);

                    return(new DavResponse()
                    {
                        Completed = true,
                        Data = sharedCardUrl
                    });
                }
                Log.Error("ERROR: " + createResponse.Error);
                throw new RadicaleException(createResponse.Error);
            }
            else
            {
                Log.Error("ERROR: " + getResponse.Error);
                throw new RadicaleException(getResponse.Error);
            }
        }