Ejemplo n.º 1
0
        public static void SelectedServer(ServerSelectionMessage message, AuthClient client)
        {
            string host      = ConfigurationManager.Instance.IsCustomHost == true ? ConfigurationManager.Instance.RealHost : ConfigurationManager.Instance.Host;
            var    encrypted = AccountsProvider.EncryptTicket(ServersManager.TransfertToGame(client.Account), client.AesKey);

            client.Send(new SelectedServerDataMessage((ushort)ConfigurationManager.Instance.ServerId, host, (ushort)ConfigurationManager.Instance.WorldPort, true, encrypted));
            client.Disconnect();
        }
Ejemplo n.º 2
0
 public void Initialize()
 {
     m_authClient = new AuthClient();
     auth         = new Auth(this);
     user         = new User(this);
     post         = new Post(this);
     notice       = new Notice(this);
     report       = new Report(this);
 }
Ejemplo n.º 3
0
 public AuthService(
     AuthClient authClient, UserClient client,
     IAuthManager authManager, ICurrentUserManager currentUserManager)
 {
     this.client             = client;
     this.currentUserManager = currentUserManager;
     this.authManager        = authManager;
     this.authClient         = authClient;
 }
Ejemplo n.º 4
0
        public void ServerSelectionMessageFrame(AuthClient client, ServerSelectionMessage serverSelectionMessage)
        {
            List <uint> ports = new List <uint>();

            ports.Add(6666);

            client.SendPacket(new SelectedServerDataMessage(serverSelectionMessage.serverId, "127.0.0.1", ports, true, AuthenticationUtils.EncodeTicket(client.salt)));
            client.Disconnect();
        }
Ejemplo n.º 5
0
        public void Setup()
        {
            AuthClient client = new AuthClient("", "", true)
            {
                RecvWindow = 60000
            };

            Endpoint = new AccountEndPoint(client);
        }
        public async Task LoginTest(string username, string password)
        {
            var client        = new AuthClient(httpClient);
            var loginResponse = await client.LoginAsync(username, password);

            Assert.NotNull(loginResponse);
            JwtTokenTest(loginResponse.Token, "thingsboard.io", username);
            JwtTokenTest(loginResponse.RefreshToken, "thingsboard.io", username);
        }
Ejemplo n.º 7
0
        private User AuthenticateUser(string sessionToken)
        {
            Guid token = Guid.Parse(sessionToken);

            AuthClient authClient = AuthenticatedClients.Instance.Clients.Values
                                    .FirstOrDefault(client => client.AuthToken.Equals(token));

            return(authClient?.User);
        }
Ejemplo n.º 8
0
        static void TcpServer_OnPacketReceived(AuthClient client, AuthPacket packet)
        {
            Console.WriteLine(DateTime.Now.ToString() + $" PACKET [{packet.Id}]");

            switch (packet.Id)
            {
            case AuthPacketEnum.SERVER_CONNECT:
            {
                var response = new AuthPacket();

                //Verifica se achave AuthKey está correta
                if (client.Key == _authKey)
                {
                    response.Message = new
                    {
                        Success = true,
                    };

                    _authServer.Send(client, response);

                    _authServer.ShowConnectedClients();
                }
                else
                {
                    response.Message = new
                    {
                        Success   = false,
                        Exception = "Chave de autenticação inválida"
                    };

                    _authServer.Send(client, response);
                    _authServer.DisconnectClient(client);
                }
            }
            break;

            case AuthPacketEnum.LS_PLAYER_DUPLCATE_LOGIN:
            {
                _authServer.SendToAll(packet);         //Envia para todos o packet DuplicateLogin
            }
            break;

            case AuthPacketEnum.SERVER_KEEPALIVE:
            {
                _authServer.Send(client, new AuthPacket()
                    {
                        Id = 0x00
                    });
            }
            break;

            default:
                Console.WriteLine("Packet ID inválido: " + packet.Id);
                break;
            }
        }
Ejemplo n.º 9
0
        public async Task <ActionResult> InitData()
        {
            return(await RunActionAsync(async() =>
            {
                var now = DateTime.Now;

                if (!await this._AuthScopeRepository.ExistAsync(null))
                {
                    var model = new AuthScope()
                    {
                        Name = "all",
                        DisplayName = "全部权限",
                        Description = "全部权限",
                        Important = (int)YesOrNoEnum.是,
                        Sort = 0,
                        IsDefault = (int)YesOrNoEnum.是,
                        ImageUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        FontIcon = "fa fa-star"
                    };
                    model.Init();

                    await this._AuthScopeRepository.AddAsync(model);
                }

                var client_id = this._IValidationDataProvider.GetClientID(this.X.context);
                var client_security = this._IValidationDataProvider.GetClientSecurity(this.X.context);

                if (!ValidateHelper.IsAllPlumpString(client_id, client_security))
                {
                    return Content("default client data is empty");
                }

                if (!await this._AuthClientRepository.ExistAsync(x => x.UID == client_id && x.ClientSecretUID == client_security))
                {
                    await this._AuthClientRepository.DeleteWhereAsync(x => x.UID == client_id || x.ClientSecretUID == client_security);
                    var official = new AuthClient()
                    {
                        UID = client_id,
                        ClientName = "auth管理端",
                        Description = "auth管理端",
                        ClientUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        LogoUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        UserUID = "http://www.baidu.com/",
                        ClientSecretUID = client_security,
                        IsRemove = (int)YesOrNoEnum.否,
                        IsActive = (int)YesOrNoEnum.是,
                        CreateTime = now,
                        UpdateTime = now
                    };

                    await this._AuthClientRepository.AddAsync(official);
                }

                return Content("ok");
            }));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Manuseia Comunicação do Cliente
        /// </summary>
        private void HandleClient(object obj)
        {
            try
            {
                //Recebe cliente a partir do parâmetro
                TcpClient tcpClient = (TcpClient)obj;

                NetworkStream clientStream = tcpClient.GetStream();

                #region READ ON CONNECT INICIAL

                AuthPacket packet = ReceivePacket(clientStream);

                var client = new AuthClient(tcpClient)
                {
                    Name = packet.Message.ServerName,
                    Type = packet.Message.ServerType,
                    Key  = packet.Message.Key
                };

                Clients.Add(client);

                ClientConnected(client);

                OnPacketReceived?.Invoke(client, packet);

                #endregion

                //Escuta contínuamente as mensagens dos clientes (Servidores) enquanto estiver conectado
                while (tcpClient.Connected)
                {
                    try
                    {
                        packet = ReceivePacket(clientStream);

                        OnPacketReceived?.Invoke(client, packet);
                    }
                    catch (Exception erro)
                    {
                        Console.WriteLine(DateTime.Now.ToString() + $" Exception error:" + Environment.NewLine);
                        Console.WriteLine(erro.Message + Environment.NewLine);

                        //Desconecta client
                        DisconnectClient(client);
                    }
                }

                //Caso o Client não estiver mais conectado
                DisconnectClient(client);
            }
            catch (Exception erro)
            {
                Console.WriteLine(DateTime.Now.ToString() + $" Exception error:" + Environment.NewLine);
                Console.WriteLine(erro.Message + Environment.NewLine);
            }
        }
Ejemplo n.º 11
0
        async void LoginButton_Clicked(object sender, EventArgs e)
        {

            if (String.IsNullOrEmpty(emailEntry.Text))
            {
                await DisplayAlert("Erro!", "Digite um email Válido", "Aceitar");
                emailEntry.Focus();
                return;
            }

            if (String.IsNullOrEmpty(senhaEntry.Text))
            {
                await DisplayAlert("Erro!", "Digite uma senha Válida", "Aceitar");
                senhaEntry.Focus();
                return;        /*FIM DA VERIFICAÇÃO DOS CAMPOS*/
            }

            UserLogin userLogin = new UserLogin() { 
                 Email = emailEntry.Text,
                 Password = senhaEntry.Text
            };
            AuthClient authClient = new AuthClient();

            var token = await authClient.Login(userLogin);
            var IsLoggedIn = true;
            if (string.IsNullOrWhiteSpace(token))
                IsLoggedIn = false;

            SetProperties("IsLoggedIn", IsLoggedIn);


            if (IsLoggedIn)
            {
                App.Current.MainPage = new NavigationPage(new PagePrincipal());
                
            }
            else
            {
                Device.BeginInvokeOnMainThread(async () =>
                {
                    var result = await this.DisplayAlert("Erro!", "Nome de Usuário ou Senha não encontrado", "Sim", "Cancelar");
                    if (result)
                    {
                        await Navigation.PushAsync(new LoginPage());
                       
                    }
                    else
                    {
                        await Navigation.PushAsync(new LoginPage());
                        
                    }

                });

            }
        }
Ejemplo n.º 12
0
        public override void HandlePacket(Packet packet)
        {
            _client     = packet.Client;
            _authClient = packet.AuthClient;
            _packet     = packet;
            _builder    = new MessageBuilder(_authClient, _client, _packet.EndPoint, _packet.SyncKey);
            switch (_packet.PacketType)
            {
            case PacketManager.PacketTypes.MouseDown:
                HandleMouseDown();
                break;

            case PacketManager.PacketTypes.MouseUp:
                HandleMouseUp();
                break;

            case PacketManager.PacketTypes.MouseScroll:
                HandleScroll();
                break;

            case PacketManager.PacketTypes.LeftDblClick:
                break;

            case PacketManager.PacketTypes.KeyDown:
                HandleKeyDown();
                break;

            case PacketManager.PacketTypes.KeyUp:
                HandleKeyUp();
                break;

            case PacketManager.PacketTypes.FullFrame:
                HandleFullFrame();
                break;

            case PacketManager.PacketTypes.RightClick:
                HandleRightClick();
                break;

            case PacketManager.PacketTypes.MouseMove:
                HandleMoveMouse();
                break;

            case PacketManager.PacketTypes.CheckScreenShare:
                CheckServer();
                break;

            case PacketManager.PacketTypes.StartScreenShare:
                StartScreenShare();
                break;

            case PacketManager.PacketTypes.StopScreenShare:
                StopScreenShare();
                break;
            }
        }
Ejemplo n.º 13
0
        public void Send(AuthClient client, AuthPacket packet)
        {
            var _stream = client.Tcp.GetStream();

            var json = JsonConvert.SerializeObject(packet);

            var result = json.Select(Convert.ToByte).ToArray();

            _stream.Write(result, 0, result.Length);
        }
Ejemplo n.º 14
0
        public void Handshake(AuthClient authClient)
        {
            var handshake = new
            {
                message   = "Handshake established",
                publicKey = Rsa.SecureStringToString(authClient.PublicKey)
            };

            MessageHandler.SendMessage("connectedToScreenShare", handshake, authClient);
        }
Ejemplo n.º 15
0
        public static void HandleServerSelection(BigEndianReader reader, AuthClient client, AuthServer server)
        {
            ServerSelectionMessage message = new ServerSelectionMessage();

            message.Unpack(reader);
            client.Send(new SelectedServerDataMessage(1, "127.0.0.1", 442, true, client.Ticket));
            client.Disconnect();
            //client.Send(new SelectedServerRefusedMessage(message.serverId, (sbyte)ServerConnectionErrorEnum.SERVER_CONNECTION_ERROR_NO_REASON, (sbyte)ServerStatusEnum.NOJOIN));
            //TODO HANDLE SERVER CONNECTION REQUEST FROM CLIENT
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Create a packet
 /// </summary>
 /// <param name="authClient"></param>
 /// <param name="endPoint"></param>
 /// <param name="syncKey"></param>
 /// <param name="args"></param>
 /// <param name="packetType"></param>
 /// <param name="packetHandler"></param>
 public Packet(AuthClient authClient, string endPoint, string syncKey, List <object> args, PacketTypes packetType,
               Type packetHandler)
 {
     AuthClient     = authClient;
     EndPoint       = endPoint;
     SyncKey        = syncKey;
     Args           = args;
     PacketType     = packetType;
     _packetHandler = packetHandler;
 }
Ejemplo n.º 17
0
        private void HandleFullFrame(AuthClient client)
        {
            var frameData = new
            {
                Screen.PrimaryScreen.Bounds,
                frameData = FullScreenData()
            };

            MessageHandler.SendMessage("frameData", frameData, client);
        }
Ejemplo n.º 18
0
 public void Indentificate(AuthClient client)
 {
     try {
         ConnectionHandler.ProcessIdentification(client);
     }
     catch (Exception ex) {
         client.Send(new IdentificationFailedMessage((sbyte)(IdentificationFailureReasonEnum.SERVICE_UNAVAILABLE)));
         this.logger.Alert(ex.ToString());
     }
 }
        public async Task LogoutAsync()
        {
            foreach (var account in await AuthClient.GetAccountsAsync())
            {
                await AuthClient.RemoveAsync(account);
            }

            _accessToken.OnNext(null);
            _authResult.OnNext(null);
        }
Ejemplo n.º 20
0
        private JRetornoAutenticacao Autenticar()
        {
            /// EndPoint para Autenticação
            string     lEndPoint = URLBase + Util.ObterParametro <string>("PUCOMEX.EndPointAutentica");
            AuthClient client    = AuthClient.Instance;

            client.CreateHttpClient(lEndPoint);

            return(client.Post(lEndPoint).Result);
        }
Ejemplo n.º 21
0
        public void GetSites_ContainsStyling()
        {
            var sites = AuthClient.GetSites();

            Assert.IsNotNull(sites);
            foreach (var site in sites)
            {
                Assert.IsNotNull(site.MainSite.Styling);
            }
        }
Ejemplo n.º 22
0
        public static void HandleIdentification(BigEndianReader reader, AuthClient client, AuthServer server)
        {
            IdentificationWithLoginTokenMessage message = new IdentificationWithLoginTokenMessage();

            message.Unpack(reader);
            Account  account = AccountManager.GetAccount(message.login);
            DateTime dateNow = DateTime.Now;

            //IF ACCOUNT EXIST
            if (account == null ||
                message.password != Tools.GetMd5(account.Password + client.Ticket)) //Test password
            {
                client.Send(new IdentificationFailedMessage((sbyte)IdentificationFailureReasonEnum.WRONG_CREDENTIALS));
                client.Disconnect();
                return;
            }
            client.account = account;
            //IF LIFE BANNED OR IP BANNED
            if (account.Banned || server.BlockedIp.Contains(client.Ip))
            {
                client.Send(new IdentificationFailedMessage((sbyte)IdentificationFailureReasonEnum.BANNED));
                client.Disconnect();
                return;
            }
            //IF TEMP BANNED
            if (account.EndBan > dateNow)
            {
                int ms = 0;
                ms = (int)account.EndBan.Subtract(dateNow).TotalMinutes;
                client.Send(new IdentificationFailedBannedMessage((sbyte)IdentificationFailureReasonEnum.BANNED, ms));
                client.Disconnect();
                return;
            }
            //IF ON MAINTENANCE
            if (AuthServer.onMaintenance && !account.isAdmin)
            {
                client.Send(new IdentificationFailedMessage((sbyte)IdentificationFailureReasonEnum.IN_MAINTENANCE));
                client.Disconnect();
                return;
            }
            //TODO QUEUE MANAGEMENT
            if (account.Pseudo == null || account.Pseudo.Length == 0)
            {
                client.Send(new NicknameRegistrationMessage());
                Out.Info($"First connection for account '{account.Username}'. Requesting a nickname.");
                return;
            }
            SendAccServer(client, server);
            //TODO AUTO CONNECT TO THE FIRST AVAILABLE SERVER
            if (message.autoconnect)
            {
                //client.Send(new SelectedServerRefusedMessage(1, (sbyte)ServerConnectionErrorEnum.SERVER_CONNECTION_ERROR_DUE_TO_STATUS, (sbyte)ServerStatusEnum.NOJOIN));
                Out.Debug(account.isAdmin ? $"+Admin {account.Pseudo}" : $"+User {account.Pseudo}");
            }
        }
        public async Task GetDownload_Test()
        {
            var response = await AuthClient.GetAsync("/api/export/download/123-Mock-321");

            var content = await response.Content.ReadAsByteArrayAsync();

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            PdfApiMock.Verify(e => e.DownloadFileAsync("mockroot/123-Mock-321.pdf", It.IsAny <string>(), It.IsAny <string>()));
            Assert.Equal("file 123-Mock-321.pdf content", Encoding.UTF8.GetString(content));
            Assert.Matches("Issues-.{4}-.{2}-.{2}.pdf", response.Content.Headers.ContentDisposition.FileNameStar);
        }
Ejemplo n.º 24
0
        public async Task SignOut()
        {
            LiveLoginResult loginResult = await AuthClient.InitializeAsync(Scopes);

            // Sign the user out, if they are connected
            if (loginResult.Status != LiveConnectSessionStatus.NotConnected)
            {
                AuthClient.Logout();
            }
            UpdateAuthProperties(LiveConnectSessionStatus.NotConnected);
        }
        public static void Authenticate(string password, string packetData, AuthClient authClient)
        {
            try
            {
                if (!packetData.IsBase64String())
                {
                    throw new InvalidOperationException("Packet must be base64 encoded if encrypted.");
                }

                if (authClient != null)
                {
                    packetData = MessageHandler.DecryptMessage(packetData, authClient);
                    if (packetData == null)
                    {
                        throw new Exception("Packet is null");
                    }
                    var args = new List <object>();
                    var deserializedPacket = JObject.Parse(packetData);
                    args.AddRange(JArray.Parse(deserializedPacket["args"].ToString()));
                    var authKey   = authClient.Client.GetHashCode().ToString();
                    var inputPass = args[0].ToString();
                    if (inputPass.Equals(password))
                    {
                        authClient.Authenticated           = true;
                        ConnectionHandler.Clients[authKey] = authClient;
                        var login = new
                        {
                            message  = "Login Valid!",
                            loggedIn = true
                        };
                        MessageHandler.SendMessage("login", login, authClient);
                    }
                    else
                    {
                        var login = new
                        {
                            message  = "Login Invalid!",
                            loggedIn = false
                        };
                        MessageHandler.SendMessage("login", login, authClient);
                    }
                }
            }
            catch (Exception e)
            {
                var login = new
                {
                    message  = "Login Failed!",
                    reason   = e.Message,
                    loggedIn = false
                };
                MessageHandler.SendMessage("login", login, authClient);
            }
        }
Ejemplo n.º 26
0
        public GameServerInformations GetServerInformation(AuthClient client, WorldServer world)
        {
            var charactersCount = client.Account.GetCharactersCountByWorld(world.Id);

            return(new GameServerInformations((short)world.Id, 1, (sbyte)world.Status,
                                              (sbyte)world.Completion,
                                              world.ServerSelectable,
                                              charactersCount,
                                              (sbyte)(charactersCount > 5 ? charactersCount : 5),
                                              DateTime.Now.GetUnixTimeStampLong()));
        }
Ejemplo n.º 27
0
        private async Task AttemptRefreshToken()
        {
            //If the user is signed in and has not yet signed out, we will attempt to refresh the token if necessary before sending a create page request
            if (IsSignedIn)
            {
                //Attempt to use the refresh token acquired previously since the user has not explicitly signed out
                LiveLoginResult loginWithRefreshTokenResult = await AuthClient.InitializeAsync(Scopes);

                UpdateAuthProperties(loginWithRefreshTokenResult.Status);
            }
        }
Ejemplo n.º 28
0
        public static byte[] DecryptFrame(byte[] data, AuthClient client)
        {
            if (client == null)
            {
                return(null);
            }
            var keyBytes = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(client.AesKey));
            var keyIv    = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(client.AesIv));

            return(UAes.DecryptFile(data, keyBytes, keyIv));
        }
Ejemplo n.º 29
0
        public async Task GetUserTest(string username, string password)
        {
            var client        = new AuthClient(httpClient);
            var loginResponse = await client.LoginAsync(username, password);

            httpClient.DefaultRequestHeaders.Add("X-Authorization", $"Bearer {loginResponse.Token}");
            var getUserResponse = await client.UserAsync();

            Assert.NotNull(getUserResponse);
            Assert.Equal(username, getUserResponse.Name);
        }
Ejemplo n.º 30
0
        public static string DecryptMessage(byte[] message, AuthClient client)
        {
            if (client != null)
            {
                var keybytes = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(client.AesKey));
                var iv       = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(client.AesIv));

                return(UAes.Decrypt(message, keybytes, iv));
            }
            return(null);
        }
Ejemplo n.º 31
0
 private void btnLogin_Click(object sender, RoutedEventArgs e)
 {
     AuthClient client = new AuthClient();
     ITestOperation testClient = new TestOperationClient();
     if(client.SignIn(txtLogin.Text, txtPassword.Text))
     {
         txtResult.Text = "Success " + testClient.GetTest().Name;
         
     }
     else
     {
         txtResult.Text = "Fail";
     }
 }
        private List<AuthClient> CreateAuthClientList()
        {
            var client = new AuthClient(WebConfigurationManager.AppSettings["ClientId"],
                WebConfigurationManager.AppSettings["Base64Secret"])
            {
                AllowedOrigin = "http://localhost:18720/",
                Application = TApplication.Web,
                Enabled = true
            };

            var collection = new List<AuthClient>();
            collection.Add(client);
            return collection;
        }
Ejemplo n.º 33
0
        public bool AccountExists(string Username, string Password, AuthClient Client)
        {
            bool Exists = false;

            SQLiteCommand Command = GetConnection().CreateCommand();
            Command.CommandText = "SELECT * FROM Accounts WHERE Username = @Username AND Password = @Password";
            Command.Parameters.Add("@Username", DbType.AnsiString).Value = Username;
            Command.Parameters.Add("@Password", DbType.AnsiString).Value = Password;

            SQLiteDataReader Reader = Command.ExecuteReader();
            while (Reader.Read())
            {
                Client.SetAccountID(Convert.ToUInt32(Reader["ID"]));
                Exists = true;
            }

            return Exists;
        }
Ejemplo n.º 34
0
 public bool AccountExists(string Username, string Password, AuthClient Client)
 {
     return AccountCtrl.AccountExists(Username, Password, Client);
 }
Ejemplo n.º 35
0
 public Service(ChatServerContext context)
     : base()
 {
     ServerContext = context;
     AuthClient = new AuthClient(context.Config);
 }
Ejemplo n.º 36
0
 public static string UploadStringOAuth2(this WebClient client, 
     IStorage storage, string scopes, string path, string queryBody)
 {
     var creds = storage.GetCredentials();
     client.AddBearer(creds);
     try
     {
         return client.UploadString(path, queryBody);
     }
     catch (WebException ex)
     {
         if (ex.Status == WebExceptionStatus.ProtocolError)
         {
             if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
                 throw;
             var secrets = storage.GetSecrets();
             var authclient = new AuthClient(secrets, scopes, null, null);
             var newcreds = authclient.refreshAuthCode(creds);
             var storedcreds = storage.StoreCredentials(newcreds);
             client.AddBearer(storedcreds);
             return client.UploadString(path, queryBody);
         }
         throw;
     }
 }