Ejemplo n.º 1
0
        //[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));
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        /// <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);
            }
        }
Ejemplo n.º 4
0
        public Task FailProofAsync(AuthStatus code)
        {
            _writer.Write((byte)AuthCommand.LogonProof);
            _writer.Write((byte)code);

            return(_writer.FlushAsync());
        }
Ejemplo n.º 5
0
        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));
            }
        }
Ejemplo n.º 6
0
 public AuthResult(AuthStatus status, String ip, int port, byte[] token)
 {
     Status = status;
     Ip     = ip;
     Port   = port;
     Token  = token;
 }
Ejemplo n.º 7
0
        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);
            }
        }
Ejemplo n.º 8
0
        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"));
        }
Ejemplo n.º 9
0
        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;
                }
            }
        }
Ejemplo n.º 10
0
 public Carrot(string appId, SecureString appSecret, string userId = null, string hostname = "gocarrot.com")
 {
     mAppId = appId;
     mAppSecret = appSecret;
     mUserId = userId;
     mHostname = hostname;
     mAuthStatus = AuthStatus.Undetermined;
 }
Ejemplo n.º 11
0
 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 });
 }
Ejemplo n.º 12
0
        public Task FailChallengeAsync(AuthStatus code)
        {
            _writer.Write((byte)AuthCommand.LogonChallenge);
            //_writer.Write((byte)0);
            _writer.Write((byte)code);

            return(_writer.FlushAsync());
        }
Ejemplo n.º 13
0
        /// <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);
        }
Ejemplo n.º 14
0
        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;
            }
        }
Ejemplo n.º 15
0
 /// <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;
 }
Ejemplo n.º 16
0
        /// <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)));
        }
Ejemplo n.º 17
0
        /// <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);
        }
Ejemplo n.º 19
0
        /// <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)));
        }
Ejemplo n.º 20
0
        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;
        }
Ejemplo n.º 21
0
        /// <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)));
        }
Ejemplo n.º 22
0
        /// <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)));
        }
Ejemplo n.º 23
0
        /// <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);
        }
Ejemplo n.º 25
0
        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); });
                }
            }
        }
Ejemplo n.º 26
0
 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;
 }
Ejemplo n.º 27
0
        /// <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);
            }
        }
Ejemplo n.º 28
0
 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 + ".");
     }
 }
Ejemplo n.º 29
0
 private static void ClientOnAuthStatus(AuthStatus status)
 {
     if (status == AuthStatus.Failed)
     {
         WriteLine("Failed to authenticate.");
     }
     if (status == AuthStatus.Success)
     {
         WriteLine("Authenticated with success.");
     }
 }
Ejemplo n.º 30
0
 public void OnGet()
 {
     if (HttpContext.User.Identity.IsAuthenticated)
     {
         UserName = HttpContext.User.Identity.Name;
         Status   = AuthStatus.Authorized;
     }
     else
     {
         Status = AuthStatus.LoggedOut;
     }
 }
Ejemplo n.º 31
0
 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;
 }
Ejemplo n.º 32
0
        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;
        }
Ejemplo n.º 33
0
        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;
        }
Ejemplo n.º 34
0
 public AuthenticationCrypto()
 {
     Status = AuthStatus.Uninitialized;
 }
Ejemplo n.º 35
0
 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!";
     }
 }
Ejemplo n.º 36
0
 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...";
     }
 }
Ejemplo n.º 37
0
 public void Pending()
 {
     Status = AuthStatus.Pending;
 }
Ejemplo n.º 38
0
 /// <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.";
     }
 }
Ejemplo n.º 39
0
        /// <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));
        }
Ejemplo n.º 40
0
 public User()
 {
     this.status = AuthStatus.NO_LOGIN;
 }
Ejemplo n.º 41
0
        /// <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));
        }
Ejemplo n.º 42
0
        /// <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));
        }
Ejemplo n.º 43
0
        /// <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;
        }
Ejemplo n.º 44
0
        /// <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;
            }
        }
Ejemplo n.º 45
0
        /// <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));
        }