//[AllowAnonymous] public async Task <IHttpActionResult> Login(LoginViewModel loginViewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } #region 设置默认返回JSON AuthStatus actionResult = new AuthStatus() { IsSuccess = true, Message = "登录成功!" }; #endregion #region 获取验证策略 var userStrategy = ApplicationContext.StrategyManager.GetDefaultStrategy <IUserAuthenticationStrategy>(); if (userStrategy == null) { actionResult = new AuthStatus() { IsSuccess = true, Message = "无法登录,没有找到登录策略!" }; return(Ok(actionResult)); } #endregion actionResult = userStrategy.Login(loginViewModel.LoginName, loginViewModel.Password, loginViewModel.RememberMe); return(Ok(actionResult)); }
private string GetAuthMessage(AuthStatus status) { string message = string.Empty; switch (status) { case AuthStatus.InvalidCredentials: message = "Invalid User ID / Password combination, please try again."; break; case AuthStatus.MaxLoginAttemptsExceeded: message = "Account is locked and may not logon, contact your Security Administrator to unlock your account."; break; case AuthStatus.PasswordExpired: message = "Password has expired, contact your Security Administrator to reset your password."; break; case AuthStatus.PasswordExpiredAllowChange: message = "Password has expired, please change your password."; break; case AuthStatus.DatabaseError: default: message = "There was a problem performing the Login request, please try again."; break; } return(message); }
/// <summary> /// Sets a permission for a page. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="pageFullName">The page full name.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="subject">The subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> private bool SetPermissionForPage(AuthStatus status, string pageFullName, string action, string subject) { if (pageFullName == null) { throw new ArgumentNullException("page"); } if (pageFullName.Length == 0) { throw new ArgumentException("Page cannot be empty", "page"); } if (action == null) { throw new ArgumentNullException("action"); } if (action.Length == 0) { throw new ArgumentException("Action cannot be empty", "action"); } if (action != Actions.FullControl && !AuthTools.IsValidAction(action, Actions.ForPages.All)) { throw new ArgumentException("Invalid action", "action"); } if (status == AuthStatus.Delete) { bool done = _settingsProvider.AclManager.DeleteEntry(Actions.ForPages.ResourceMasterPrefix + pageFullName, action, subject); if (done) { Log.LogEntry(MessageDeleteSuccess + GetLogMessage(Actions.ForPages.ResourceMasterPrefix, pageFullName, action, subject, Delete), EntryType.General, Log.SystemUsername, _settingsProvider.CurrentWiki); } else { Log.LogEntry(MessageDeleteFailure + GetLogMessage(Actions.ForPages.ResourceMasterPrefix, pageFullName, action, subject, Delete), EntryType.Error, Log.SystemUsername, _settingsProvider.CurrentWiki); } return(done); } else { bool done = _settingsProvider.AclManager.StoreEntry(Actions.ForPages.ResourceMasterPrefix + pageFullName, action, subject, status == AuthStatus.Grant ? Value.Grant : Value.Deny); if (done) { Log.LogEntry(MessageSetSuccess + GetLogMessage(Actions.ForPages.ResourceMasterPrefix, pageFullName, action, subject, Set + status.ToString()), EntryType.General, Log.SystemUsername, _settingsProvider.CurrentWiki); } else { Log.LogEntry(MessageSetFailure + GetLogMessage(Actions.ForPages.ResourceMasterPrefix, pageFullName, action, subject, Set + status.ToString()), EntryType.Error, Log.SystemUsername, _settingsProvider.CurrentWiki); } return(done); } }
public Task FailProofAsync(AuthStatus code) { _writer.Write((byte)AuthCommand.LogonProof); _writer.Write((byte)code); return(_writer.FlushAsync()); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl = "/admin/empresas") { AuthStatus result = LoginGeral(model); switch (result) { case AuthStatus.OK: return(Redirect(returnUrl)); case AuthStatus.USER_BLOQUED: ModelState.AddModelError("", "Este usuário está bloqueado. Contate o suporte técnico."); return(View(model)); case AuthStatus.USER_CANCELED: case AuthStatus.USER_NOT_EXISTS: ModelState.AddModelError("", "O usuário informado nao existe."); return(View(model)); case AuthStatus.INVALID_USERNAME: case AuthStatus.INVALID_PASSWORD: ModelState.AddModelError("", "Usuário ou senha estão incorretos."); return(View(model)); default: ModelState.AddModelError("", "Erro ao efetuar o login. Contate o suporte técnico."); return(View(model)); } }
public AuthResult(AuthStatus status, String ip, int port, byte[] token) { Status = status; Ip = ip; Port = port; Token = token; }
private void loginLogic(string username, string password) { JObject obj = new APICaller("auth.php").addParam("username", username).addParam("password", password).call(); if (obj["status"].ToString() == "success") { LocalUser localUser = new LocalUser { Username = obj["user"]["username"].ToString(), FirstName = obj["user"]["firstName"].ToString(), LastName = obj["user"]["lastName"].ToString(), KarmaPoints = obj["user"]["karmaPoints"].ToObject <int>(), IsLecturer = Convert.ToBoolean(obj["user"]["lecturer"].ToObject <int>()), PrivateKey = obj["user"]["privateKey"].ToString(), ProfilePictureLocation = obj["user"]["profilePicture"].ToString() }; LoginResult(AuthStatus.Success, localUser); } else { AuthStatus status = AuthStatus.UnknownError; if (!Enum.TryParse <AuthStatus>(obj["message"].ToString(), out status)) { status = AuthStatus.UnknownError; } LoginResult(status, null); } }
public async Task <IActionResult> OnPostAsync() { var targetUser = await _context.Admins.AsNoTracking().FirstOrDefaultAsync(t => t.Login == Admin.Login); if (targetUser == null) { Status = AuthStatus.Error; return(Page()); } if (!_encryption.VerifyPassword(Admin.Password, targetUser.Password)) { Status = AuthStatus.Error; return(Page()); } Admin.Role = targetUser.Role; Admin.LastChanged = targetUser.LastChanged; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(GetIdentity()), new AuthenticationProperties { IsPersistent = true }); UserName = Admin.Login; Status = AuthStatus.Authorized; return(RedirectToPage("./Index")); }
public async Task RunAsync(TcpClient client) { _client = client; var ipaddr = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString(); _client.ReceiveTimeout = 1000; var seedArr = new byte[4]; new Random().NextBytes(seedArr); _mseed = seedArr; _clientStream = _client.GetStream(); _reader = new AsyncBinaryReader(_clientStream); _writer = new BinaryWriter(_clientStream); _status = AuthStatus.UNAUTHED; Debug.WriteLine("Connection from " + ipaddr); SendAuthChallenge(); while (_run) { var lb1 = _ac.decrypt((await _reader.ReadBytesAsync(1)))[0]; var lb2 = _ac.decrypt((await _reader.ReadBytesAsync(1)))[0]; var len = (lb1 << 8) + lb2; Debug.WriteLine(lb1 + "|" + lb2 + " ->| " + len); var wp = new WorldPacket(await _reader.ReadBytesAsync(len), this); Debug.WriteLine("INCOMING COM:" + wp.cmd + " SIZE:" + len); switch (wp.cmd) { case WorldCommand.CMSG_AUTH_SESSION: await HandleAuthSession(wp); break; case WorldCommand.CMSG_PING: if (_status != AuthStatus.AUTHED) //Should not be pinging if not authed { Close(); } else { HandlePing(wp); } break; default: if (_session == null || _status == AuthStatus.UNAUTHED) //Should not be sending anything else right now. Should also be authed by now { Close(); } else { _session.HandlePacket(wp); } break; } } }
public Carrot(string appId, SecureString appSecret, string userId = null, string hostname = "gocarrot.com") { mAppId = appId; mAppSecret = appSecret; mUserId = userId; mHostname = hostname; mAuthStatus = AuthStatus.Undetermined; }
public void handle(AuthStatus curStatus, WorldSession ws, WorldPacket com) { if (curStatus < _authStatus) { throw new Exception("Auth status not good enough"); } _func.Invoke(ws, new object[] { com }); }
public Task FailChallengeAsync(AuthStatus code) { _writer.Write((byte)AuthCommand.LogonChallenge); //_writer.Write((byte)0); _writer.Write((byte)code); return(_writer.FlushAsync()); }
/// <summary> /// Login to the system using email address, password, online status, device type, and spam filter options /// </summary> /// <param name="email">The email address for the bot's account</param> /// <param name="password">The password for the bot's account</param> /// <param name="auth">The Auth status (Online, offline, invisible) to sign in with</param> /// <param name="type">The device type to sign in with</param> /// <param name="spamfilter">Whether or not to apply spam filter</param> public void Login(string email, string password, AuthStatus auth = AuthStatus.Online, DeviceType type = DeviceType.PC, bool spamfilter = false) { var settings = new Settings(email, password, auth, type, spamfilter, true); Login(settings); }
void Update() { if (_authStatus == AuthStatus.NeedAuth) { _authStatus = AuthStatus.Authing; if (_authThread != null) { if (_authThread.IsAlive) { _authThread.Abort(); } _authThread = null; } _authThread = new Thread(new ThreadStart(startAuth)); _authThread.Start(); } if (_authFinish && _retNum != null && _retText != null) { _authFinish = false; Debug.Log(_retNum); Debug.Log(_retText); if (_retNum != "200") { //UIManager.getInstance().ShowMessage(_retText, 2.0f); CallMethod("OnLoginAuthFail", _retText); } else { //开始连接游戏服务器 int posOne = _retText.IndexOf("@"); int posTwo = _retText.IndexOf(":"); int posThree = _retText.IndexOf("#"); int posFour = _retText.IndexOf("&"); string subId = _retText.Substring(0, posOne); string address = _retText.Substring(posOne + 1, posTwo - posOne - 1); int port = int.Parse(_retText.Substring(posTwo + 1, posThree - posTwo - 1)); string serverName = _retText.Substring(posThree + 1, posFour - posThree - 1); string uid = _retText.Substring(posFour + 1); //开始连接游戏服务器 Debug.Log("修改"); //AppFacade.Instance.GetManager<NetworkManager>(ManagerName.Network).finishAuth(address, port, serverName, subId, uid, AppConst.Platform, secret); //NetWorkManager.getInstance().finishAuth(address, port, serverName, subId, uid, Global.getInstance().Platform, secret); CallMethod("OnLoginAuthSuccess", address, port, serverName, subId, uid, secret); } _retNum = null; _retText = null; } }
/// <summary> /// Constructor /// </summary> /// <param name="email"></param> /// <param name="password"></param> /// <param name="vis"></param> /// <param name="device"></param> /// <param name="spamfilter"></param> /// <param name="trackmessages"></param> public Settings(string email, string password, AuthStatus vis, DeviceType device, bool spamfilter, bool trackmessages) { Email = email; Password = password; Visibility = vis; Device = device; SpamFilter = spamfilter; TrackMessages = trackmessages; }
/// <summary> /// Sets a permission for a global resource. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="user">The user subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public bool SetPermissionForGlobals(AuthStatus status, string action, UserInfo user) { if (user == null) { throw new ArgumentNullException("user"); } return(SetPermissionForGlobals(status, action, AuthTools.PrepareUsername(user.Username))); }
/// <summary> /// Sets a permission for a namespace. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="nspace">The namespace (<c>null</c> for the root).</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="user">The user subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public static bool SetPermissionForNamespace(AuthStatus status, NamespaceInfo nspace, string action, UserInfo user) { if (user == null) { throw new ArgumentNullException("user"); } return(SetPermissionForNamespace(status, nspace, action, AuthTools.PrepareUsername(user.Username))); }
private AuthStatus TokenAuthentication(string token, string ipAddress) { AuthStatus authStatus = AuthStatus.None; _apiToken = NetCacheHelper.GetValue(token) as TokenApplyPlace; if (_apiToken == null || DateTime.Now > _apiToken.ExpireDateTime) { using (SqlConnection conn = new SqlConnection(_DBconfig)) { String strQuery = @"SELECT top 1 Token, ExpireDateTime, ApplicationName, AllowIPs from dbo.Token LEFT JOIN dbo.Application ON dbo.Application.Id = dbo.Token.ApplicationID where Token = @token"; conn.Open(); _apiToken = conn.Query <TokenApplyPlace>(strQuery, new { token = token }).SingleOrDefault(); if (_apiToken != null && DateTime.Now < _apiToken.ExpireDateTime) { //token未過期才緩存 //set cache //NetCacheHelper.Add(token, _apiToken, _apiToken.ExpireDateTime); } } } if (_apiToken == null) { //ToKen是否已存在 authStatus = AuthStatus.Revoked_TokenNotExists; } else if (DateTime.Now > _apiToken.ExpireDateTime) { //ToKen是否過期 authStatus = AuthStatus.Revoked_Expired; } else if (String.IsNullOrWhiteSpace(_apiToken.ApplicationName)) { //ToKen是否有相關的系統在使用 authStatus = AuthStatus.Revoked_AppNotExists; } else if (!String.IsNullOrWhiteSpace(ipAddress) && !String.IsNullOrWhiteSpace(_apiToken.AllowIPs) && !ipAddress.Equals("::1") && !ipAddress.Equals("127.0.0.1") && !_apiToken.AllowIPs.Contains(ipAddress) ) { //IP權限判斷,判斷使用者IP是否可以使用此API authStatus = AuthStatus.Revoked_NotAllowIP; } else { //驗證通過 authStatus = AuthStatus.Authorized; } return(authStatus); }
/// <summary> /// Sets a permission for a global resource. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="group">The group subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public bool SetPermissionForGlobals(AuthStatus status, string action, UserGroup group) { if (group == null) { throw new ArgumentNullException("group"); } return(SetPermissionForGlobals(status, action, AuthTools.PrepareGroup(group.Name))); }
private async Task CloseAsync(AuthStatus errorCode) { await SendErrorAsync(errorCode); await Task.Delay(300); // Give the packet some time to be sent _client.Close(); _run = false; }
/// <summary> /// Sets a permission for a directory. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="provider">The provider that handles the directory.</param> /// <param name="directory">The directory.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="group">The group subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV40 provider, string directory, string action, UserGroup group) { if (group == null) { throw new ArgumentNullException("group"); } return(SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareGroup(group.Name))); }
/// <summary> /// Sets a permission for a page. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="page">The page.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="group">The group subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public static bool SetPermissionForPage(AuthStatus status, PageInfo page, string action, UserGroup group) { if (group == null) { throw new ArgumentNullException("group"); } return(SetPermissionForPage(status, page, action, AuthTools.PrepareGroup(group.Name))); }
/// <summary> /// Sets a permission for a directory. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="provider">The provider that handles the directory.</param> /// <param name="directory">The directory.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="user">The user subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV40 provider, string directory, string action, UserInfo user) { if (user == null) { throw new ArgumentNullException("user"); } return(SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareUsername(user.Username))); }
public override void OnActionExecuting(ActionExecutingContext Context) { var _request = Context.HttpContext.Request; var httpurl = new Uri(_request.Scheme + "://" + _request.Host); string ipAppress = Context.HttpContext.Connection.RemoteIpAddress.ToString(); string Path = string.Empty; if (_request.Path.HasValue) { Path = _request.Path.Value; } string AuthorizationHeader = _request.Headers["Authorization"].ToString().Trim(); //版本不對 if (Context.HttpContext.Request.Path.Value.IndexOf("/V2/", StringComparison.OrdinalIgnoreCase) >= 0) { //沒有加入token if (string.IsNullOrWhiteSpace(AuthorizationHeader)) { _authStatus = AuthStatus.Revoked_AuthorizationNotExists; } //token 格式不對 else if (!(AuthorizationHeader.StartsWith("basic" + _delimiter, StringComparison.OrdinalIgnoreCase))) { _authStatus = AuthStatus.Revoked_AuthorizationFormatIncorrect; } //取得token驗證 else { _token = AuthorizationHeader.Split(_delimiter)[1].Trim(); _authStatus = TokenAuthentication(_token, ipAppress, Path, (httpurl.Scheme + "://" + httpurl.Host).ToString()); } } else { _authStatus = AuthStatus.Revoked_ErrorUrlPath; } if (_authStatus != AuthStatus.Authorized) { Context.Result = new JsonResult(new ResponseBase <String>() { rCode = _authStatus.Get_rCode(), rDesc = _authStatus.Get_rCodeDesc() }); } else { Context.HttpContext.Items[API_Developers_Info] = _apiToken; } base.OnActionExecuting(Context); }
protected async void CheckForExistingLoginAsync(AuthValidationMode authValidationMode, AuthenticationMode authMode) { string serializedAuthStatus = AuthManager.Instance.RetrieveProtectedString(Constants.AuthStatusKey); if (!String.IsNullOrEmpty(serializedAuthStatus)) { var aS = AuthStatus.DeserializeFromString(serializedAuthStatus); //consider that a change in Authmode is possible between versions of an app, so check if the saved token may be trusted if (AuthenticationMode.Authorize.Equals(authMode) && !aS.IsAuthorized || AuthenticationMode.Identify.Equals(authMode) && aS.IsAuthorized) { return; } if (NetworkInterface.GetIsNetworkAvailable()) { this.VM.IsShowOverlay = true; try { SystemTray.ProgressIndicator.IsVisible = true; if (await aS.CheckIfStillValidAsync()) { AuthManager.Instance.CurrentAuthStatus = aS; NavigationService.Navigate(AuthManager.Instance.SuccessRedirect); } else { Dispatcher.BeginInvoke(() => { MessageBox.Show(LocalizedStrings.LocalizedResources.AuthNoMemberError); }); } } catch (WebTransferException) { if (AuthValidationMode.Graceful.Equals(authValidationMode)) { NavigationService.Navigate(AuthManager.Instance.SuccessRedirect); } else { Dispatcher.BeginInvoke(() => { MessageBox.Show(LocalizedStrings.LocalizedResources.AuthNetworkError); }); } } finally { SystemTray.ProgressIndicator.IsVisible = false; this.VM.IsShowOverlay = false; } } else { if (AuthValidationMode.Graceful.Equals(authValidationMode)) { NavigationService.Navigate(AuthManager.Instance.SuccessRedirect); } Dispatcher.BeginInvoke(() => { MessageBox.Show(LocalizedStrings.LocalizedResources.AuthNetworkError); }); } } }
public AuthResult(AuthStatus status, string message, string accessToken, string refreshToken, DateTimeOffset?expires, User_Model user) { Status = status; Message = message; AccessToken = accessToken; RefreshToken = refreshToken; TokenExpires = expires; User = user; }
/// <summary> /// Sets a permission for a namespace. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="nspace">The namespace (<c>null</c> for the root).</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="subject">The subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> private static bool SetPermissionForNamespace(AuthStatus status, NamespaceInfo nspace, string action, string subject) { if (action == null) { throw new ArgumentNullException("action"); } if (action.Length == 0) { throw new ArgumentException("Action cannot be empty", "action"); } if (action != Actions.FullControl && !AuthTools.IsValidAction(action, Actions.ForNamespaces.All)) { throw new ArgumentException("Invalid action", "action"); } string namespaceName = nspace != null ? nspace.Name : ""; if (status == AuthStatus.Delete) { bool done = SettingsProvider.AclManager.DeleteEntry(Actions.ForNamespaces.ResourceMasterPrefix + namespaceName, action, subject); if (done) { Log.LogEntry(MessageDeleteSuccess + GetLogMessage(Actions.ForNamespaces.ResourceMasterPrefix, namespaceName, action, subject, Delete), EntryType.General, Log.SystemUsername); } else { Log.LogEntry(MessageDeleteFailure + GetLogMessage(Actions.ForNamespaces.ResourceMasterPrefix, namespaceName, action, subject, Delete), EntryType.Error, Log.SystemUsername); } return(done); } else { bool done = SettingsProvider.AclManager.StoreEntry(Actions.ForNamespaces.ResourceMasterPrefix + namespaceName, action, subject, status == AuthStatus.Grant ? Value.Grant : Value.Deny); if (done) { Log.LogEntry(MessageSetSuccess + GetLogMessage(Actions.ForNamespaces.ResourceMasterPrefix, namespaceName, action, subject, Set + status), EntryType.General, Log.SystemUsername); } else { Log.LogEntry(MessageSetFailure + GetLogMessage(Actions.ForNamespaces.ResourceMasterPrefix, namespaceName, action, subject, Set + status), EntryType.Error, Log.SystemUsername); } return(done); } }
private static void ListenerOnAuthStatus(IClientInfo client, AuthStatus status) { if (status == AuthStatus.Failed) { WriteLine("Server failed to authenticate certificate of client " + client.Id + " " + client.Guid + "."); } if (status == AuthStatus.Success) { WriteLine("Server authenticate certificate of client " + client.Id + " " + client.Guid + "."); } }
private static void ClientOnAuthStatus(AuthStatus status) { if (status == AuthStatus.Failed) { WriteLine("Failed to authenticate."); } if (status == AuthStatus.Success) { WriteLine("Authenticated with success."); } }
public void OnGet() { if (HttpContext.User.Identity.IsAuthenticated) { UserName = HttpContext.User.Identity.Name; Status = AuthStatus.Authorized; } else { Status = AuthStatus.LoggedOut; } }
public Carrot(string appId, string appSecret, string userId, string hostname = "gocarrot.com") { mAppSecret = new SecureString(); foreach(char c in appSecret) { mAppSecret.AppendChar(c); } mAppId = appId; mUserId = userId; mHostname = hostname; mAuthStatus = AuthStatus.Undetermined; }
public static void Initialize(byte[] sessionKey) { // create RC4-drop[1024] stream encryptionStream = new ARC4(outputHMAC.ComputeHash(sessionKey)); encryptionStream.Process(new byte[1024], 0, 1024); // create RC4-drop[1024] stream decryptionStream = new ARC4(inputHMAC.ComputeHash(sessionKey)); decryptionStream.Process(new byte[1024], 0, 1024); Status = AuthStatus.Ready; }
public AuthenticationCrypto() { Status = AuthStatus.Uninitialized; }
private static string GetAuthFailStatusString(AuthStatus authStatus) { string message = "RelentlessZero: "; switch (authStatus) { case AuthStatus.InvalidCredentials: return message += "Invalid account credentials!"; case AuthStatus.BannedTemporary: return message += "Account is temporary closed, try again later."; case AuthStatus.BannedPermently: return message += "Account is permently closed due to abuse."; case AuthStatus.AlreadySignedIn: return message += "Account is already signed in, try again later."; case AuthStatus.InternalError: default: return message += "An internal error has occurred!"; } }
void UpdateAuthStatusText(AuthStatus s) { if (s == AuthStatus.LoggedIn) { label_authStatus.ForeColor = Color.Green; label_authStatus.Text = "Logged in"; } else if (s == AuthStatus.NotLoggedIn) { label_authStatus.ForeColor = Color.FromArgb(192, 0, 0); label_authStatus.Text = "Not logged in"; } else { label_authStatus.ForeColor = Color.Black; label_authStatus.Text = "Logging in..."; } }
public void Pending() { Status = AuthStatus.Pending; }
/// <summary> /// Return the string value of an <see cref="AuthStatus"/> value. /// </summary> /// <returns>The string description of an <see cref="AuthStatus"/>.</returns> public static string authStatusString(AuthStatus authStatus) { switch(authStatus) { case Carrot.AuthStatus.NotAuthorized: return "Carrot user has not authorized the application."; case Carrot.AuthStatus.Undetermined: return "Carrot user status is undetermined."; case Carrot.AuthStatus.ReadOnly: return "Carrot user has not allowed the 'publish_actions' permission."; case Carrot.AuthStatus.Ready: return "Carrot user is authorized."; default: return "Invalid Carrot AuthStatus."; } }
/// <summary> /// Sets a permission for a directory. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="provider">The provider that handles the directory.</param> /// <param name="directory">The directory.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="group">The group subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public static bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV30 provider, string directory, string action, UserGroup group) { if(group == null) throw new ArgumentNullException("group"); return SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareGroup(group.Name)); }
public User() { this.status = AuthStatus.NO_LOGIN; }
/// <summary> /// Sets a permission for a directory. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="provider">The provider that handles the directory.</param> /// <param name="directory">The directory.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="user">The user subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public static bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV30 provider, string directory, string action, UserInfo user) { if(user == null) throw new ArgumentNullException("user"); return SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareUsername(user.Username)); }
/// <summary> /// Sets a permission for a page. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="page">The page.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="group">The group subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public static bool SetPermissionForPage(AuthStatus status, PageInfo page, string action, UserGroup group) { if(group == null) throw new ArgumentNullException("group"); return SetPermissionForPage(status, page, action, AuthTools.PrepareGroup(group.Name)); }
/// <summary> /// Executes the required requests. /// </summary> /// <returns>the result of the required requests. Succeeded or Failed.</returns> internal ExitCode ExecuteRequiredRequests() { // execute authentication request and check authentication status // before executing other requests IAuthRequest authRequest = RequiredRequests.OfType<IAuthRequest>().First(); DoRequest(authRequest); IResponse response = _connection.GetResponse(); if (response is IAuthResponse) { ProcessResponse(response); _status = ((IAuthResponse) response).Status; } else { while (response != null) { Responses.Add(response); response = _connection.GetResponse(); } ////var responses = _connection.GetAllResponses(); ////Responses = Responses.Union(responses).ToList(); _status = AuthStatus.Error; } if (_status == AuthStatus.Authenticated) { IEnumerable<IRequest> otherRequests = RequiredRequests.Where(r => r.Type != RequestType.Auth && r.Type != RequestType.VerifyAuth); foreach (IRequest request in otherRequests) { DoRequest(request); if (request.ResponseExpected) { ProcessRequestResponses(); } } } // set the valid requests list var validRequestResponse = (ValidRequestsResponse) Responses.Where(r => r.Type == ResponseType.ValidRequests).FirstOrDefault(); if (validRequestResponse != null) { ValidRequestTypes = validRequestResponse.ValidRequestTypes; } ProcessMessages(); if (!PServerHelper.IsTestMode()) RequiredRequests.Clear(); // remove requests already processed bool hasErrorResponse = Responses.Where(r => r.Type == ResponseType.Error).Count() > 0 ? true : false; bool hasOkResponse = Responses.Where(r => r.Type == ResponseType.Ok).Count() > 0 ? true : false; Responses = Responses.Where(r => !r.Processed).ToList(); // removed processed responses ExitCode code; if (hasErrorResponse) code = ExitCode.Failed; else if (hasOkResponse && _status == AuthStatus.Authenticated) code = ExitCode.Succeeded; else if (_status != AuthStatus.Authenticated) code = ExitCode.Failed; else code = ExitCode.Unknown; return code; }
/// <summary> /// Sets a permission for a page. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="page">The page.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="subject">The subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> private static bool SetPermissionForPage(AuthStatus status, PageInfo page, string action, string subject) { if(page == null) throw new ArgumentNullException("page"); if(action == null) throw new ArgumentNullException("action"); if(action.Length == 0) throw new ArgumentException("Action cannot be empty", "action"); if(action != Actions.FullControl && !AuthTools.IsValidAction(action, Actions.ForPages.All)) { throw new ArgumentException("Invalid action", "action"); } if(status == AuthStatus.Delete) { bool done = SettingsProvider.AclManager.DeleteEntry(Actions.ForPages.ResourceMasterPrefix + page.FullName, action, subject); if(done) { Log.LogEntry(MessageDeleteSuccess + GetLogMessage(Actions.ForPages.ResourceMasterPrefix, page.FullName, action, subject, Delete), EntryType.General, Log.SystemUsername); } else { Log.LogEntry(MessageDeleteFailure + GetLogMessage(Actions.ForPages.ResourceMasterPrefix, page.FullName, action, subject, Delete), EntryType.Error, Log.SystemUsername); } return done; } else { bool done = SettingsProvider.AclManager.StoreEntry(Actions.ForPages.ResourceMasterPrefix + page.FullName, action, subject, status == AuthStatus.Grant ? Value.Grant : Value.Deny); if(done) { Log.LogEntry(MessageSetSuccess + GetLogMessage(Actions.ForPages.ResourceMasterPrefix, page.FullName, action, subject, Set + status.ToString()), EntryType.General, Log.SystemUsername); } else { Log.LogEntry(MessageSetFailure + GetLogMessage(Actions.ForPages.ResourceMasterPrefix, page.FullName, action, subject, Set + status.ToString()), EntryType.Error, Log.SystemUsername); } return done; } }
/// <summary> /// Sets a permission for a page. /// </summary> /// <param name="status">The authorization status.</param> /// <param name="page">The page.</param> /// <param name="action">The action of which to modify the authorization status.</param> /// <param name="user">The user subject of the authorization change.</param> /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns> public static bool SetPermissionForPage(AuthStatus status, PageInfo page, string action, UserInfo user) { if(user == null) throw new ArgumentNullException("user"); return SetPermissionForPage(status, page, action, AuthTools.PrepareUsername(user.Username)); }