internal async Task <Tuple <bool, string> > ConfigureCredential( string ownerUri, CredentialInfo credential, ConfigAction configAction, RunType runType) { return(await Task <Tuple <bool, string> > .Run(() => { try { ConnectionInfo connInfo; ConnectionServiceInstance.TryFindConnection(ownerUri, out connInfo); CDataContainer dataContainer = CDataContainer.CreateDataContainer(connInfo, databaseExists: true); using (CredentialActions actions = new CredentialActions(dataContainer, credential, configAction)) { var executionHandler = new ExecutonHandler(actions); executionHandler.RunNow(runType, this); } return new Tuple <bool, string>(true, string.Empty); } catch (Exception ex) { return new Tuple <bool, string>(false, ex.ToString()); } })); }
public static async Task CleanupCredential( TestConnectionResult connectionResult, CredentialInfo credential) { var service = new SecurityService(); await SecurityTestUtils.DeleteCredential(service, connectionResult, credential); }
private async void AddAction() { CustomDialog customDialog = new CustomDialog() { Title = LocalizationManager.GetStringByKey("String_Header_AddCredential") }; CredentialViewModel credentialViewModel = new CredentialViewModel(instance => { dialogCoordinator.HideMetroDialogAsync(this, customDialog); CredentialInfo credentialInfo = new CredentialInfo { ID = instance.ID, Name = instance.Name, Username = instance.Username, Password = instance.Password }; CredentialManager.AddCredential(credentialInfo); TimerLockUIStart(); // Reset timer }, instance => { dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, CredentialManager.GetNextID()); customDialog.Content = new CredentialDialog { DataContext = credentialViewModel }; await dialogCoordinator.ShowMetroDialogAsync(this, customDialog); }
public void CredentialManagerCanSetAndGetCredentialInfoMachine() { CredentialManager mgr = new CredentialManager(GetTestCredentialVault()); CredentialInfo info1 = new CredentialInfo { UserName = "******", Password = "******", TargetService = "MyAwesomeService1", MachineName = "Machine1" }; CredentialInfo info2 = new CredentialInfo { UserName = "******", Password = "******", TargetService = "MyAwesomeService2" }; mgr.SetCredentials(info1); mgr.SetCredentials(info2); CredentialInfo check1 = mgr.GetCredentials(info1.MachineName, info1.TargetService); CredentialInfo check2 = mgr.GetCredentials(info2.TargetService); Expect.AreEqual(info1.UserName, check1.UserName); Expect.AreEqual(info1.Password, check1.Password); Expect.AreEqual(info1.TargetService, check1.TargetService); Expect.IsNull(info2.MachineName); Expect.IsFalse(info1.Password.Equals(check2.Password)); Expect.AreEqual(info2.UserName, check2.UserName); Expect.AreEqual(info2.Password, check2.Password); Expect.AreEqual(info2.TargetService, check2.TargetService); }
public void HttpPostPassingTest() { CredentialInfo credentialInfo = new CredentialInfo() { identityServerURL = ConnectionConst.IDENTITYSERVERURL, identityServerClientID = ConnectionConst.IDENTITYSERVERCLIENTID, identityServerClientSecrets = ConnectionConst.IDENTITYSERVERCLIENTSECRETS, identityServerScopes = ConnectionConst.IDENTITYSERVERSCOPES, identityServerUsername = ConnectionConst.IDENTITYSERVERUSERNAME, identityServerPassword = ConnectionConst.IDENTITYSERVERPASSWORD }; ManageRequest manageRequest = new ManageRequest(credentialInfo, ConnectionConst.APISERVERURL); Dictionary <string, string> ValidateUserNameAndPasswordInput = new Dictionary <string, string>() { { "userName", "test_f" }, { "userPasswordHash", "bb96c2fc40d2d54617d6f276febe571f623a8dadf0b734855299b0e107fda32cf6b69f2da32b36445d73690b93cbd0f7bfc20e0f7f28553d2a4428f23b716e90" } }; HttpContent ValidateUserNameAndPasswordInputContent = new StringContent( JsonConvert.SerializeObject(ValidateUserNameAndPasswordInput), Encoding.UTF8, "application/json"); HttpResponseMessage httpResponse = manageRequest.HttpPost(ConnectionConst.POSTREQUESTURL, ValidateUserNameAndPasswordInputContent).Result; Assert.Equal(httpResponse.StatusCode, HttpStatusCode.OK); }
public static SafeTokenHandle GetImpersonationToken(this CredentialInfo credentialInfo, bool isCurrentSystemLogon) { Requires.NotNull(credentialInfo, nameof(credentialInfo)); Requires.NotNullOrEmpty(credentialInfo.UserName, nameof(credentialInfo.UserName)); Requires.NotNullOrEmpty(credentialInfo.Password, nameof(credentialInfo.Password)); return(GetImpersonationToken(credentialInfo.UserName, credentialInfo.Password, isCurrentSystemLogon)); }
public CredentialsViewModel(IDialogCoordinator instance) { dialogCoordinator = instance; _credentials = CollectionViewSource.GetDefaultView(CredentialManager.Credentials); _credentials.SortDescriptions.Add(new SortDescription(nameof(CredentialInfo.ID), ListSortDirection.Ascending)); _credentials.Filter = o => { if (string.IsNullOrEmpty(Search)) { return(true); } CredentialInfo info = o as CredentialInfo; string search = Search.Trim(); // Search by: Name, Username return(info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.Username.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); }; CheckCredentialsLoaded(); // Set up dispatcher timer _dispatcherTimer = new DispatcherTimer(); _dispatcherTimer.Tick += _dispatcherTimer_Tick; _dispatcherTimer.Interval = new TimeSpan(0, 0, 1); }
public void CredentialManagerReturnsNullForUnkownUser() { CredentialManager mgr = new CredentialManager(GetTestCredentialVault()); CredentialInfo info1 = new CredentialInfo { UserName = "******", Password = "******", TargetService = "MyAwesomeService1", MachineName = "Machine1" }; CredentialInfo info2 = new CredentialInfo { UserName = "******", Password = "******", TargetService = "MyAwesomeService2" }; mgr.SetCredentials(info1); mgr.SetCredentials(info2); CredentialInfo info = mgr.GetCredentials(9.RandomLetters()); Expect.IsNullOrEmpty(info.UserName); Expect.IsNullOrEmpty(info.Password); Expect.IsTrue(info.IsNull); }
// Remove a specific uri/auth combination. public void Remove(Uri uriPrefix, String authType) { CredentialInfo info = list; CredentialInfo last = null; while (info != null) { #if !ECMA_COMPAT if (info.uriPrefix.Equals(uriPrefix) && String.Compare(info.authType, authType, true, CultureInfo.InvariantCulture) == 0) #else if (info.uriPrefix.Equals(uriPrefix) && String.Compare(info.authType, authType, true) == 0) #endif { if (last != null) { last.next = info.next; } else { list = info.next; } return; } last = info; info = info.next; } }
public bool LockUserAccount(LoginInfo login, PasswordPolicy passwordpolicy) //if incorect only { var isLocked = false; IManagerCredential crd = new ManagerCredential(); ILayoutManager layoutManager = new LayoutManager(); IReviewCredential ReviewCredential = new ReviewCredential(); Guid tenantId = layoutManager.GetTenantId(InfoType.Tenant, login.TenantCode); CredentialInfo usercredentialinfo = UserCredentailInfo(login); if (passwordpolicy.LockoutAttempt.Value != null) { int?userpermissablelockoutAttemptcount = 1; if (usercredentialinfo.InvalidAttemptCount == null || usercredentialinfo.InvalidAttemptCount == 0) { usercredentialinfo.InvalidAttemptCount = 1; } userpermissablelockoutAttemptcount = Convert.ToInt32(passwordpolicy.LockoutAttempt.Value); if (usercredentialinfo.InvalidAttemptCount >= userpermissablelockoutAttemptcount) {//lock the user IManagerCredential managecredential = new ManagerCredential(); managecredential.UpdateLockedStatus(tenantId, usercredentialinfo.CredentialId, true, usercredentialinfo.InvalidAttemptCount, DateTime.UtcNow); isLocked = true; } else //invalid attempt count increses { IManagerCredential managecredential = new ManagerCredential(); managecredential.UpdateLockedStatus(tenantId, usercredentialinfo.CredentialId, false, usercredentialinfo.InvalidAttemptCount + 1, null); } } return(isLocked); }
public bool CheckIfLocked(LoginInfo login, PasswordPolicy passwordpolicy) { CredentialInfo usercredentialinfo = UserCredentailInfo(login); if (passwordpolicy.LockoutDuration.Value == null) { return(false); } if (usercredentialinfo.IsLocked) { //user was locked down now as time is over he is locked out if (DateTime.UtcNow > usercredentialinfo.LockedOn.AddMinutes(Convert.ToInt32(passwordpolicy.LockoutDuration.Value))) { IManagerCredential managecredential = new ManagerCredential(); IManagerCredential crd = new ManagerCredential(); ILayoutManager layoutManager = new LayoutManager(); IReviewCredential ReviewCredential = new ReviewCredential(); Guid tenantId = layoutManager.GetTenantId(InfoType.Tenant, login.TenantCode); var userId = crd.GetUserName(tenantId, login.UserName); managecredential.UpdateLockedStatus(tenantId, usercredentialinfo.CredentialId, false, 0, null); return(false); } else { return(true); } } else { return(false); } }
private void LogConnectionInfo() { RoyalRDSConnection rdpData = Data as RoyalRDSConnection; bool autologon = rdpData.TemporaryGet(() => { return(rdpData.CredentialAutologon); }); CredentialInfo effectiveCred = rdpData.TemporaryGet(() => { return(rdpData.GetEffectiveCredential()); }); string hostname = rdpData.TemporaryGet(() => { return(rdpData.URI.ResolveTokensApi(rdpData)); }); int port = rdpData.TemporaryGet(() => { return(rdpData.RDPPort); }); string username = string.Empty; string password = string.Empty; if (autologon && effectiveCred != null) { username = effectiveCred.Username; password = effectiveCred.Password; } int screenWidth = 0; int screenHeight = 0; rdpData.TemporaryAction(() => { if (rdpData.DesktopWidth == 0 && rdpData.DesktopHeight == 0) { NSView connectionPlaceholderView = TabViewItem.View.CastTo <NSView>(); screenWidth = (int)connectionPlaceholderView.Frame.Width; screenHeight = (int)connectionPlaceholderView.Frame.Height; } else { screenWidth = rdpData.DesktopWidth; screenHeight = rdpData.DesktopHeight; } }); bool console = rdpData.TemporaryGet(() => { return(rdpData.ConnectToAdministerOrConsole); }); StringBuilder details = new StringBuilder(); details.AppendLine(string.Format("Hostname: {0}", hostname)); details.AppendLine(string.Format("Port: {0}", port)); details.AppendLine(string.Format("Console: {0}", console)); details.AppendLine(string.Format("AutoLogon: {0}", autologon)); details.AppendLine(string.Format("Username: {0}", username)); details.AppendLine(string.Format("Password: {0}", password)); details.AppendLine(string.Format("Resolution: {0}x{1}", screenWidth, screenHeight)); ApiUtils.Log.Add(new RoyalLogEntry() { Severity = RoyalLogEntry.Severities.Debug, Action = "DummyConnection", PluginID = PLUGIN_ID, PluginName = PLUGIN_NAME, Message = "Connection Info", Details = details.ToString() }); }
private async void ConnectProfileAs() { CustomDialog customDialog = new CustomDialog() { Title = LocalizationManager.GetStringByKey("String_Header_ConnectAs") }; RemoteDesktopConnectViewModel remoteDesktopConnectViewModel = new RemoteDesktopConnectViewModel(instance => { dialogCoordinator.HideMetroDialogAsync(this, customDialog); ConfigurationManager.Current.IsDialogOpen = false; Models.RemoteDesktop.RemoteDesktopSessionInfo session = new Models.RemoteDesktop.RemoteDesktopSessionInfo { Hostname = instance.Host }; if (instance.UseCredentials) { session.CustomCredentials = true; if (instance.CustomCredentials) { session.Username = instance.Username; session.Password = instance.Password; } else { CredentialInfo credentialInfo = CredentialManager.GetCredentialByID((int)instance.CredentialID); session.Username = credentialInfo.Username; session.Password = credentialInfo.Password; } } Connect(session, instance.Name); }, instance => { dialogCoordinator.HideMetroDialogAsync(this, customDialog); ConfigurationManager.Current.IsDialogOpen = false; }, true) { // Set name, hostname Name = SelectedProfile.Name, Host = SelectedProfile.RemoteDesktop_Host, // Request credentials UseCredentials = true }; customDialog.Content = new RemoteDesktopConnectDialog { DataContext = remoteDesktopConnectViewModel }; ConfigurationManager.Current.IsDialogOpen = true; await dialogCoordinator.ShowMetroDialogAsync(this, customDialog); }
private async void ConnectSessionAsAction() { CustomDialog customDialog = new CustomDialog() { Title = Application.Current.Resources["String_Header_ConnectAs"] as string }; RemoteDesktopSessionConnectViewModel connectRemoteDesktopSessionViewModel = new RemoteDesktopSessionConnectViewModel(instance => { dialogCoordinator.HideMetroDialogAsync(this, customDialog); ConfigurationManager.Current.FixAirspace = false; Models.RemoteDesktop.RemoteDesktopSessionInfo remoteDesktopSessionInfo = new Models.RemoteDesktop.RemoteDesktopSessionInfo { Hostname = instance.Host }; if (instance.UseCredentials) { remoteDesktopSessionInfo.CustomCredentials = true; if (instance.CustomCredentials) { remoteDesktopSessionInfo.Username = instance.Username; remoteDesktopSessionInfo.Password = instance.Password; } else { CredentialInfo credentialInfo = CredentialManager.GetCredentialByID((int)instance.CredentialID); remoteDesktopSessionInfo.Username = credentialInfo.Username; remoteDesktopSessionInfo.Password = credentialInfo.Password; } } ConnectSession(remoteDesktopSessionInfo, instance.Name); }, instance => { dialogCoordinator.HideMetroDialogAsync(this, customDialog); ConfigurationManager.Current.FixAirspace = false; }, true) { // Set name, hostname Name = SelectedSession.Name, Host = SelectedSession.Host, // Request credentials UseCredentials = true }; customDialog.Content = new RemoteDesktopSessionConnectDialog { DataContext = connectRemoteDesktopSessionViewModel }; ConfigurationManager.Current.FixAirspace = true; await dialogCoordinator.ShowMetroDialogAsync(this, customDialog); }
private async void ConnectNewSession(string host = null) { CustomDialog customDialog = new CustomDialog() { Title = LocalizationManager.GetStringByKey("String_Header_Connect") }; RemoteDesktopSessionConnectViewModel remoteDesktopSessionConnectViewModel = new RemoteDesktopSessionConnectViewModel(instance => { dialogCoordinator.HideMetroDialogAsync(this, customDialog); ConfigurationManager.Current.FixAirspace = false; // Add host to history AddHostToHistory(instance.Host); // Create new remote desktop session info Models.RemoteDesktop.RemoteDesktopSessionInfo remoteDesktopSessionInfo = new Models.RemoteDesktop.RemoteDesktopSessionInfo { Hostname = instance.Host }; if (instance.UseCredentials) { remoteDesktopSessionInfo.CustomCredentials = true; if (instance.CustomCredentials) { remoteDesktopSessionInfo.Username = instance.Username; remoteDesktopSessionInfo.Password = instance.Password; } else { CredentialInfo credentialInfo = CredentialManager.GetCredentialByID((int)instance.CredentialID); remoteDesktopSessionInfo.Username = credentialInfo.Username; remoteDesktopSessionInfo.Password = credentialInfo.Password; } } Connect(remoteDesktopSessionInfo); }, instance => { dialogCoordinator.HideMetroDialogAsync(this, customDialog); ConfigurationManager.Current.FixAirspace = false; }) { Host = host }; customDialog.Content = new RemoteDesktopSessionConnectDialog { DataContext = remoteDesktopSessionConnectViewModel }; ConfigurationManager.Current.FixAirspace = true; await dialogCoordinator.ShowMetroDialogAsync(this, customDialog); }
bool IUserTaskManager.ResetPassword(Guid tenantId, Guid userId) { var queryFilter = new List <QueryFilter>(); queryFilter.Add(new QueryFilter { FieldName = "TenantId", Operator = "Equal", Value = tenantId.ToString() }); queryFilter.Add(new QueryFilter { FieldName = "InternalId", Operator = "Equal", Value = userId.ToString() }); var queryContext = new QueryContext { Fields = "FirstName,LastName,MiddleName,UserCredential.Username", Filters = queryFilter, PageSize = 100, PageIndex = 1, MaxResult = 1 }; byte[] passwordHash, passwordSalt; Random random = new Random(); int pass = random.Next(1000000); // pass=1234; SqlMembershipProvider.CreatePasswordHash(pass.ToString(), out passwordHash, out passwordSalt); DataTable dataTableUser = _iEntityResourceManager.GetResultById(tenantId, "user", userId, queryContext); User userEntity = EntityMapper <User> .Mapper(dataTableUser); if (Guid.Parse(userEntity.InternalId.Value) == Guid.Empty) { return(false); } CredentialInfo credentialData = crd.GetCredential(tenantId, Guid.Parse(userEntity.InternalId.Value)); var jObject = DataUtility.ConvertToJObjectList(dataTableUser); jObject[0].Add(new JProperty("UserCredential.Username", credentialData.UserName.ToString())); jObject[0].Add(new JProperty("UserCredential.Password", pass.ToString())); var emailTemplate = _iEntityResourceManager.GetWellKnownTemplate(tenantId, "emailtemplate", "user", (int)ContextTypeEnum.Forgotpassword, jObject[0]); if (emailTemplate != null && emailTemplate.Body != null) { CredentialInfo usercredentialinfo = crd.GetCredential(tenantId, userId); bool isnew = _sqlMembership.CheckResetOnFirstLogin(tenantId); crd.Update(tenantId, new CredentialInfo { CredentialId = credentialData.CredentialId, ParentId = Guid.Parse(userEntity.InternalId.Value), PasswordHash = Convert.ToBase64String(passwordHash), PasswordSalt = Convert.ToBase64String(passwordSalt), IsNew = isnew }); var returnVal = DataUtility.SaveEmail(tenantId, Guid.Parse(userEntity.InternalId.Value), emailTemplate, credentialData.UserName.ToString(), "ResetPassword", InfoType.User); } else { return(false); } return(true); }
// Remove the 'CredentialInfo' object from the list that matches to the given 'Uri' and 'AuthenticationType' public void Remove(Uri uriObj, String authenticationType) { for (int index = 0; index < arrayListObj.Count; index++) { CredentialInfo credentialInfo = (CredentialInfo)arrayListObj[index]; if (uriObj.Equals(credentialInfo.uriObj) && authenticationType.Equals(credentialInfo.authenticationType)) { arrayListObj.RemoveAt(index); } } }
/// <summary> /// 获取认证信息 /// </summary> /// <returns></returns> public static CredentialInfo GetCredentialInfo() { CredentialInfo _creinfo = new CredentialInfo(); _creinfo.UserID = TypeConverter.StrToInt(Utils.GetCookie("userid"), 0); _creinfo.Password = Utils.GetCookie("password"); if (App.GetInitParmas.ContainsKey("authToken") && !string.IsNullOrEmpty(App.GetInitParmas["authToken"])) _creinfo.AuthToken = App.GetInitParmas["authToken"]; return _creinfo; }
public CredentialInfo UserCredentailInfo(LoginInfo login) { IManagerCredential crd = new ManagerCredential(); ILayoutManager layoutManager = new LayoutManager(); IManagerRole roleManager = new ManagerRole(); Guid tenantId = layoutManager.GetTenantId(InfoType.Tenant, login.TenantCode); Guid userId = crd.GetUserName(tenantId, login.UserName); CredentialInfo credentialData = crd.GetCredential(tenantId, userId); return(credentialData); }
public NetworkCredential GetCredential(Uri uriObj, String authenticationType) { for (int index = 0; index < arrayListObj.Count; index++) { CredentialInfo credentialInfoObj = (CredentialInfo)arrayListObj[index]; if (uriObj.Equals(credentialInfoObj.uriObj) && authenticationType.Equals(credentialInfoObj.authenticationType)) { return(credentialInfoObj.networkCredentialObj); } } return(null); }
public bool ChangePasswordUpdateCredential(ChangePasswordInfo changepassword) { IManagerCredential crd = new ManagerCredential(); ILayoutManager layoutManager = new LayoutManager(); IManagerRole roleManager = new ManagerRole(); if (string.IsNullOrEmpty(changepassword.TenantCode) || string.IsNullOrEmpty(changepassword.UserName) || string.IsNullOrEmpty(changepassword.OldPassword) || string.IsNullOrEmpty(changepassword.NewPassword)) { return(false); } //Get tenant id with code Guid tenantId = layoutManager.GetTenantId(InfoType.Tenant, changepassword.TenantCode); if (tenantId == Guid.Empty) { return(false); } //Validate UserName var userId = crd.GetUserName(tenantId, changepassword.UserName); if (userId == Guid.Empty) { return(false); } //Validate UserName var passwordSaved = crd.GetPassword(tenantId, changepassword.UserName); if (passwordSaved == null) { return(false); } // check if password is correct if (!VerifyPasswordHash(changepassword.OldPassword, Convert.FromBase64String(passwordSaved.PasswordHash), Convert.FromBase64String(passwordSaved.PasswordSalt))) { return(false); } byte[] passwordHash, passwordSalt; CreatePasswordHash(changepassword.NewPassword, out passwordHash, out passwordSalt); CredentialInfo credentialData = crd.GetCredential(tenantId, userId); return(crd.Update(tenantId, new CredentialInfo { CredentialId = credentialData.CredentialId, ParentId = userId, UserName = changepassword.UserName, PasswordHash = Convert.ToBase64String(passwordHash), PasswordSalt = Convert.ToBase64String(passwordSalt), IsNew = false })); }
/// <summary> /// required when loading from Object Explorer context /// </summary> /// <param name="context"></param> public CredentialActions( CDataContainer context, CredentialInfo credential, ConfigAction configAction) { this.DataContainer = context; this.credential = credential; this.configAction = configAction; this.credentialData = new CredentialData(context, credential); this.credentialData.Initialize(); }
internal bool Delete(Guid tenantId, CredentialInfo info) { try { var cmd = CreateProcedureCommand("dbo.Credential_Delete"); cmd.AppendGuid("@guidTenantId", tenantId); cmd.AppendGuid("@guidCredentialId", info.CredentialId); cmd.AppendGuid("@guidParentId", info.ParentId); ExecuteCommand(cmd); return(true); } catch (SqlException e) { throw ReportAndTranslateException(e, "Credential ::Credential_Delete"); } }
// Implement the IEnumerator interface. public bool MoveNext() { if (next != null) { current = next; next = current.next; return(true); } else { return(false); } }
internal static async Task DeleteCredential( SecurityService service, TestConnectionResult connectionResult, CredentialInfo credential) { var context = new Mock <RequestContext <ResultStatus> >(); await service.HandleDeleteCredentialRequest(new DeleteCredentialParams { OwnerUri = connectionResult.ConnectionInfo.OwnerUri, Credential = credential }, context.Object); context.VerifyAll(); }
/// <summary> /// 获取认证信息 /// </summary> /// <returns></returns> public static CredentialInfo GetCredentialInfo() { CredentialInfo _creinfo = new CredentialInfo(); _creinfo.UserID = TypeConverter.StrToInt(Utils.GetCookie("userid"), 0); _creinfo.Password = Utils.GetCookie("password"); if (App.GetInitParmas.ContainsKey("authToken") && !string.IsNullOrEmpty(App.GetInitParmas["authToken"])) { _creinfo.AuthToken = App.GetInitParmas["authToken"]; } return(_creinfo); }
// Determine if we have a credential match. private static bool Matches(CredentialInfo info, Uri uriPrefix, String authType) { #if !ECMA_COMPAT if (String.Compare(info.authType, authType, true, CultureInfo.InvariantCulture) != 0) #else if (String.Compare(info.authType, authType, true) != 0) #endif { return(false); } return(info.uriPrefix.IsPrefix(uriPrefix)); }
/// <summary> /// 加载配置参数 /// </summary> /// <param name="initParams"></param> private void LoadConfiguration(IDictionary <string, string> initParams) { string tryTest = string.Empty; //加载定制配置信息串 _customParams = initParams["forumid"]; if (initParams.ContainsKey("MaxUploads") && !string.IsNullOrEmpty(initParams["MaxUploads"])) { int.TryParse(initParams["MaxUploads"], out _maxUpload); } if (initParams.ContainsKey("MaxFileSizeKB") && !string.IsNullOrEmpty(initParams["MaxFileSizeKB"])) { if (int.TryParse(initParams["MaxFileSizeKB"], out _maxFileSize)) { _maxFileSize = _maxFileSize * 1024; } } if (initParams.ContainsKey("FileFilter") && !string.IsNullOrEmpty(initParams["FileFilter"])) { _fileFilter = initParams["FileFilter"]; } if (initParams.ContainsKey("forumid") && !string.IsNullOrEmpty(initParams["forumid"])) { _forumid = Utils.StrToInt(initParams["forumid"], 0); } if (initParams.ContainsKey("max") && !string.IsNullOrEmpty(initParams["max"])) { _maxAttachments = Utils.StrToInt(initParams["max"], 0); } CredentialInfo _creInfo = Utils.GetCredentialInfo(); if (_creInfo.UserID <= 0) { ShowMessageBox("您未登陆系统"); SetUploadButton(false); return; } else { MixObjectsSoapClient _client = Utils.CreateServiceClient(); _client.GetAttachmentUploadSetCompleted += new EventHandler <GetAttachmentUploadSetCompletedEventArgs>(_client_GetAttachmentUploadSetCompleted); _client.GetAttachmentUploadSetAsync(_creInfo, _forumid); } }
private static CredentialInfo ReadInfo(SqlDataReader reader) { var role = new CredentialInfo { CredentialId = reader.IsDBNull(0) ? Guid.Empty : reader.GetGuid(0), ParentId = reader.IsDBNull(1) ? Guid.Empty : reader.GetGuid(1), UserName = reader.IsDBNull(2) ? string.Empty : reader.GetString(2), IsNew = reader.IsDBNull(3) ? false : reader.GetBoolean(3), InvalidAttemptCount = reader.IsDBNull(4) ? (int?)null : reader.GetInt32(4), IsLocked = reader.IsDBNull(5) ? false : reader.GetBoolean(5), LockedOn = reader.IsDBNull(6) ? DateTime.MinValue : reader.GetDateTime(6), PasswordChangedOn = reader.IsDBNull(7) ? DateTime.MinValue : reader.GetDateTime(7) }; return(role); }
internal bool SetIsNew(Guid tenantId, CredentialInfo info) { try { var cmd = CreateProcedureCommand("dbo.Credential_SetIsNew"); cmd.AppendGuid("@guidTenantId", tenantId); cmd.AppendGuid("@guidCredentialId", info.CredentialId); cmd.AppendGuid("@guidParentId", info.ParentId); cmd.AppendBit("@bitIsNew", info.IsNew); cmd.AppendDateTime("@datecurrentdate", DateTime.UtcNow); ExecuteCommand(cmd); return(true); } catch (SqlException e) { throw ReportAndTranslateException(e, "Credential ::SetIsNew"); } }
public CredentialViewModel(Action <CredentialViewModel> saveCommand, Action <CredentialViewModel> cancelHandler, int id, CredentialInfo credentialInfo = null) { _saveCommand = new RelayCommand(p => saveCommand(this)); _cancelCommand = new RelayCommand(p => cancelHandler(this)); _credentialInfo = credentialInfo ?? new CredentialInfo(); ID = id; Name = _credentialInfo.Name; Username = _credentialInfo.Username; Password = _credentialInfo.Password; _isBeingEdited = credentialInfo != null; _isLoading = false; }
/// <summary> /// WEB权限认证 /// </summary> /// <param name="creinfo">认证信息</param> /// <returns>是否通过验正</returns> private bool AuthenticateUser(CredentialInfo creinfo) { if (creinfo.UserID > 0) { int olid = Discuz.Forum.OnlineUsers.GetOlidByUid(creinfo.UserID); if (olid > 0) { OnlineUserInfo oluserinfo = Discuz.Forum.OnlineUsers.GetOnlineUser(olid); if (oluserinfo.Userid == creinfo.UserID && Utils.UrlEncode(Discuz.Forum.ForumUtils.SetCookiePassword(oluserinfo.Password.Trim(), GeneralConfigs.GetConfig().Passwordkey)) == creinfo.Password)//检测用户id和口令 { return true; } } } return false; }
public bool SaveAvatar(string fileName, byte[] data, int dataLength, string parameters, bool firstChunk, bool lastChunk, CredentialInfo creinfo, Point point, Size size) { if (AuthenticateUser(creinfo)) { string fileextname = Utils.CutString(fileName, fileName.LastIndexOf(".") + 1).ToLower(); string uploadFolder = GetAvatarUploadFolder(creinfo.UserID.ToString()); string tempFileName = fileName + _tempExtension; if (firstChunk) { //删除临时文件 if (File.Exists(@HostingEnvironment.ApplicationPhysicalPath + "/upload/temp/" + tempFileName)) File.Delete(@HostingEnvironment.ApplicationPhysicalPath + "/upload/temp/" + tempFileName); //删除目录文件 if (File.Exists(uploadFolder + "/" + fileName)) File.Delete(uploadFolder + "/" + fileName); } FileStream fs = File.Open(@HostingEnvironment.ApplicationPhysicalPath + "/upload/temp/" + tempFileName, FileMode.Append); fs.Write(data, 0, dataLength); fs.Close(); if (lastChunk) { lock (lockHelper) { string newfilename = (Environment.TickCount & int.MaxValue).ToString() + new Random().Next(1000, 9999) + "." + fileextname; File.Move(HostingEnvironment.ApplicationPhysicalPath + "/upload/temp/" + tempFileName, Utils.GetMapPath(uploadFolder + "/" + newfilename)); GrabImage(creinfo, Utils.GetMapPath(uploadFolder + "/" + newfilename), point, size); return true; } } } return false; }
// Determine if we have a credential match. private static bool Matches(CredentialInfo info, Uri uriPrefix, String authType) { #if !ECMA_COMPAT if(String.Compare(info.authType, authType, true, CultureInfo.InvariantCulture) != 0) #else if(String.Compare(info.authType, authType, true) != 0) #endif { return false; } return info.uriPrefix.IsPrefix(uriPrefix); }
//[WebMethod] //public string GetAvatarUrl() //{ // //当支持FTP上传头像时,使用FTP上传远程头像 // if (FTPs.GetForumAvatarInfo.Allowupload == 1) // return FTPs.GetForumAvatarInfo.Remoteurl; // else // return ""; //} /// <summary> /// WEB权限认证 /// </summary> /// <param name="creinfo">认证信息</param> /// <returns>是否通过验正</returns> private bool AuthenticateUser(CredentialInfo creinfo) { if (creinfo.UserID > 0) { int olid = Discuz.Forum.OnlineUsers.GetOlidByUid(creinfo.UserID); if (olid > 0) { OnlineUserInfo oluserinfo = Discuz.Forum.OnlineUsers.GetOnlineUser(olid); //if (oluserinfo.Userid == creinfo.UserID && Utils.UrlEncode(Discuz.Forum.ForumUtils.SetCookiePassword(oluserinfo.Password, GeneralConfigs.GetConfig().Passwordkey)) == creinfo.Password &&//检测用户id和口令 // creinfo.AuthToken == Discuz.Common.DES.Encode(oluserinfo.Olid.ToString() + "," + oluserinfo.Username.ToString(), oluserinfo.Password.Substring(0, 10)).Replace("+", "["))//检查认证信息 if (oluserinfo.Userid == creinfo.UserID && Utils.UrlEncode(Discuz.Forum.ForumUtils.SetCookiePassword(oluserinfo.Password, GeneralConfigs.GetConfig().Passwordkey)) == creinfo.Password)//检测用户id和口令 { return true; } } } return false; }
/// <summary> /// 截取指定位置的图片信息 /// </summary> /// <param name="filePathName"></param> /// <param name="point"></param> /// <param name="size"></param> /// <returns></returns> private bool GrabImage(CredentialInfo creinfo, string filePathName, Point point, Size size) { if(!System.IO.File.Exists(filePathName)) return false; Image oldImage = System.Drawing.Image.FromFile(filePathName); if (size.Width > oldImage.Width || size.Height > oldImage.Height) { oldImage.Dispose(); return false; } //用指定的大小和格式初始化 Bitmap 类的新实例 Bitmap bitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb); Color backColor = Color.Black;// bitmap.GetPixel(1, 1); bitmap.MakeTransparent(backColor); //从指定的 Image 对象创建新 Graphics 对象 Graphics graphics = Graphics.FromImage(bitmap); // 0,0 是graphics的起始位置,也就是从原点开始画 // new Rectangle是截取源图片的目标区域,用户只需要改变其中四个值即可 graphics.DrawImage(oldImage /*是原图片*/, 0, 0, new Rectangle(point.X, point.Y, size.Width, size.Height), GraphicsUnit.Pixel); // 将Bitmap转化成Image Image image = Image.FromHbitmap(bitmap.GetHbitmap()); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) ici = codec; } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; qualityParam[0] = 100; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; string uid = Avatars.FormatUid(creinfo.UserID.ToString()); string avatarFileName = string.Format("{0}avatars/upload/{1}/{2}/{3}/{4}_avatar_", BaseConfigs.GetForumPath, uid.Substring(0, 3), uid.Substring(3, 2), uid.Substring(5, 2), uid.Substring(7, 2)); avatarFileName = Utils.GetMapPath(avatarFileName); image.Save(avatarFileName + "large.jpg", ici, encoderParams); if (size.Width * 0.8 <= 130)//前台模版宽度 { Thumbnail.MakeThumbnailImage(avatarFileName + "large.jpg", avatarFileName + "medium.jpg", (int)(size.Width * 0.8), (int)(size.Height * 0.8)); Thumbnail.MakeThumbnailImage(avatarFileName + "large.jpg", avatarFileName + "small.jpg", (int)(size.Width * 0.6), (int)(size.Height * 0.6)); } else { Thumbnail.MakeThumbnailImage(avatarFileName + "large.jpg", avatarFileName + "medium.jpg", (int)(size.Width * 0.5), (int)(size.Height * 0.5)); Thumbnail.MakeThumbnailImage(avatarFileName + "large.jpg", avatarFileName + "small.jpg", (int)(size.Width * 0.3), (int)(size.Height * 0.3)); } try { oldImage.Dispose(); System.IO.File.Delete(filePathName); } catch { } //当支持FTP上传头像时,使用FTP上传远程头像 ////if (FTPs.GetForumAvatarInfo.Allowupload == 1) //{ // FTPs ftps = new FTPs(); // string ftpAvatarFileName = string.Format("/avatars/upload/{0}/{1}/{2}/", // uid.Substring(0, 3), uid.Substring(3, 2), uid.Substring(5, 2)); // ftps.UpLoadFile(ftpAvatarFileName, avatarFileName + "large.jpg", FTPs.FTPUploadEnum.ForumAvatar); // ftps.UpLoadFile(ftpAvatarFileName, avatarFileName + "medium.jpg", FTPs.FTPUploadEnum.ForumAvatar); // ftps.UpLoadFile(ftpAvatarFileName, avatarFileName + "small.jpg", FTPs.FTPUploadEnum.ForumAvatar); //} return true; }
// Remove a specific uri/auth combination. public void Remove(Uri uriPrefix, String authType) { CredentialInfo info = list; CredentialInfo last = null; while(info != null) { #if !ECMA_COMPAT if(info.uriPrefix.Equals(uriPrefix) && String.Compare(info.authType, authType, true, CultureInfo.InvariantCulture) == 0) #else if(info.uriPrefix.Equals(uriPrefix) && String.Compare(info.authType, authType, true) == 0) #endif { if(last != null) { last.next = info.next; } else { list = info.next; } return; } last = info; info = info.next; } }
// Constructor. public CredentialEnumerator(CredentialCache cache) { this.cache = cache; this.current = null; this.next = cache.list; }
// Implement the IEnumerator interface. public bool MoveNext() { if(next != null) { current = next; next = current.next; return true; } else { return false; } }
public void Reset() { current = null; next = cache.list; }
public List<ShowtopicPageAttachmentInfo> GetAttachList(int topicid, int forumid, string onlyauthor, int posterid, CredentialInfo creinfo) { TopicInfo topic = Topics.GetTopicInfo(topicid); ForumInfo forum = Forums.GetForumInfo(forumid); UserInfo userinfo = new UserInfo(); UserGroupInfo usergroupinfo = UserGroups.GetUserGroupInfo(7);//默认为游客 if (AuthenticateUser(creinfo)) { userinfo = Users.GetUserInfo(creinfo.UserID); usergroupinfo = UserGroups.GetUserGroupInfo(userinfo.Groupid); } // 取得用户权限id,1管理员,2超版,3版主,0普通组,-1特殊组 int ismoder = Moderators.IsModer(usergroupinfo.Radminid, userinfo.Uid, forumid) ? 1 : 0; int price = GetTopicPrice(topic, creinfo, ismoder); return GetAttachList(price, onlyauthor, ismoder, posterid, userinfo, usergroupinfo, topic, forum); }
/// <summary> /// 获取主题价格 /// </summary> /// <param name="topicInfo"></param> /// <returns></returns> private int GetTopicPrice(TopicInfo topicInfo, CredentialInfo creinfo, int ismoder) { int price = 0; if (topicInfo.Special == 0)//普通主题 { //购买帖子操作 //判断是否为购买可见帖, price=0为非购买可见(正常), price>0 为购买可见, price=-1为购买可见但当前用户已购买 if (topicInfo.Price > 0 && creinfo.UserID != topicInfo.Posterid && ismoder != 1) { price = topicInfo.Price; //时间乘以-1是因为当Configs.GetMaxChargeSpan()==0时,帖子始终为购买帖 if (PaymentLogs.IsBuyer(topicInfo.Tid, creinfo.UserID) ||(Utils.StrDateDiffHours(topicInfo.Postdatetime, Scoresets.GetMaxChargeSpan()) > 0 && Scoresets.GetMaxChargeSpan() != 0)) //判断当前用户是否已经购买 { price = -1; } } } return price; }
}; // class CredentialInfo // Constructor. public CredentialCache() { list = null; }
// Add credentials to this cache. public void Add(Uri uriPrefix, String authType, NetworkCredential cred) { if(uriPrefix == null) { throw new ArgumentNullException("uriPrefix"); } if(authType == null) { throw new ArgumentNullException("authType"); } CredentialInfo info = list; CredentialInfo last = null; while(info != null) { #if !ECMA_COMPAT if(info.uriPrefix.Equals(uriPrefix) && String.Compare(info.authType, authType, true, CultureInfo.InvariantCulture) == 0) #else if(info.uriPrefix.Equals(uriPrefix) && String.Compare(info.authType, authType, true) == 0) #endif { throw new ArgumentException (S._("Arg_DuplicateCredentials")); } last = info; info = info.next; } info = new CredentialInfo(); info.uriPrefix = uriPrefix; info.authType = authType; info.cred = cred; info.next = null; if(last != null) { last.next = info; } else { list = info; } }