public string post(LoginAuthentication auth)
        {
            string email = auth.Email.ToString();
            LoginAuthentication Usercheck = ctx.Auth.SingleOrDefault(d => d.Email == email);

            if (Usercheck != null)
            {
                if (Usercheck.Password == auth.Password)
                {
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
                    string resp = Usercheck.AuthToken.ToString();
                    return(resp);
                }
                else
                {
                    string resp = "error matching pass";
                    return(resp);
                    //return Request.CreateResponse(HttpStatusCode.Forbidden);
                }
            }
            else
            {
                string resp = "error login";
                return(resp);
                //return Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }
        //        public ActionResult<Customer> Post([FromBody] Customer value)

        public ActionResult <Customer> Post([FromBody] LoginAuthentication value)
        {
            using (CustomerRepository cr = new CustomerRepository())
            {
                Customer customer = cr.FindByEmailAndPW(value.Email, value.PassWord);
                return(customer);
            }
        }
 public ModelService <UsuarioTokenAuthentication> Post([FromBody] LoginAuthentication value)
 {
     return(TryExecute(() =>
     {
         var secretKey = _configuration.GetSection("Jwt").GetValue <string>("SecretKey");
         return this._authenticationAppService.Logar(value, secretKey);
     }));
 }
Exemple #4
0
 public Student GetStudent(LoginAuthentication login)
 {
     if (login == null)
     {
         return(null);
     }
     return(db.Students.SingleOrDefault(student => student.Firstname == login.Firstname &&
                                        student.Lastname == login.Lastname &&
                                        student.Password == login.Password));
 }
Exemple #5
0
        private void createButton_Click(object sender, EventArgs e)
        {
            //insert into the db
            var cred      = new Credentials(accountBox.Text, pw1Box.Text, emailBox.Text);
            var isSuccess = LoginAuthentication.IsInsertDb(_conn, cred);

            if (isSuccess)
            {
                this.Close();
            }
        }
        public void InvalidUserIdTest()
        {
            SdkConfig config = new SdkConfig()
            {
                CompanyId    = "testcompany",
                UserId       = null,
                UserPassword = "******",
            };

            LoginAuthentication loginAuth = new LoginAuthentication(config);
        }
Exemple #7
0
        public LoginAuthentication DataGuest()
        {
            LoginAuthentication guest = new LoginAuthentication
            {
                Login     = "******",
                Password  = "******",
                LastDate  = DateTime.Now,
                LimitDate = DateTime.Now.AddDays(5),
                Remember  = false,
                Features  = Features()
            };

            return(guest);
        }
Exemple #8
0
        public void WriteXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<authentication>
    <login>
        <userid>testuser</userid>
        <companyid>testcompany</companyid>
        <password>testpass</password>
    </login>
</authentication>";

            LoginAuthentication loginAuth = new LoginAuthentication("testuser", "testcompany", "testpass");

            this.CompareXml(expected, loginAuth);
        }
        public LoginData UserAuthentication(String user, String pass)
        {
            LoginData           loginData = new LoginData();
            LoginAuthentication login     = new LoginAuthentication();

            if (login.CredentialsAuthentication(user, pass).Equals(validationResult.Success))
            {
                loginData.TipoUsuario = login.GetUserType(user, pass);
                loginData.Result      = validationResult.Success;
            }
            else
            {
                loginData.Result = validationResult.UserOrPasswordIncorrect;
            }
            return(loginData);
        }
Exemple #10
0
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Validator v = new Validator();

            if (!v.isPresent(txtUsername))
            {
                //show error message
            }
            else if (!v.isPresent(txtPassword))
            {
                //show error message
            }
            else
            {
                try
                {
                    LoginAuthentication l = new LoginAuthentication();
                    string pass           = l.GetLoginInfo(connString, txtUsername.Text);

                    if (pass == null)
                    {
                        lbl_error_message.Text = "enter valid password or username";
                        //error message->enter valid password or username
                    }
                    else
                    {
                        if (pass != txtPassword.Text)
                        {
                            lbl_error_message.Text = "enter valid password or username";
                            //error message->enter valid password or username
                        }
                        else
                        {
                            Session["username"] = txtUsername.Text;
                            Session["pass"]     = txtPassword.Text;
                            Response.Redirect("main.aspx", true);
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Exemple #11
0
        public bool Register(UserRegister userRegister)
        {
            LoginAuthentication       loginAuthentication = null;
            RegistroUsuarioSoapClient acessoSoapClient    = Settings.DefiniServer.Instance(LanguageDefault).SetConfigRegistroUsuarioService();

            if (acessoSoapClient == null)
            {
                ReconnectRegister(userRegister);
            }

            XElement xElement = acessoSoapClient.RegistrarUsuario(userRegister.UserName, userRegister.Password, userRegister.FirstName, userRegister.LastName, userRegister.CPF, userRegister.Email, userRegister.District, userRegister.CEP, userRegister.City, userRegister.Complement, userRegister.Birthday.Value.ToString("MM/dd/yyyy 00:00:00"), userRegister.State, userRegister.Street, userRegister.Number, ((int)userRegister.Tipo).ToString());

            XmlDocument xmlServer = new XmlDocument();

            using (XmlReader xmlReader = xElement.CreateReader())
            {
                xmlServer.Load(xmlReader);
            }

            acessoSoapClient.Close();

            xmlServer.ChildNodes[0].InnerXml = Utility.Decript(xmlServer.ChildNodes[0].InnerXml);

            if (xmlServer.DocumentElement != null)
            {
                XmlNode xmlFechamento = xmlServer.DocumentElement.SelectSingleNode("FECHAMENTO");

                XmlNode xmlLogin = xmlServer.DocumentElement.SelectSingleNode("LOGIN");

                XmlNode xmlSenha = xmlServer.DocumentElement.SelectSingleNode("PASSWORD");

                XmlNode xmlInformacao = xmlServer.DocumentElement.SelectSingleNode("INFORMACAO");

                if ((xmlFechamento == null) || (xmlFechamento.InnerText != "1"))
                {
                    throw new Exception(xmlInformacao.InnerText);
                    return(false);
                }
            }

            return(true);
        }
        public async Task <ActionResult <UsuarioTokenAuthentication> > Autenticar([FromBody] LoginAuthentication usuario)
        {
            var usuarioResult = await _context.Usuarios.FirstOrDefaultAsync(x => x.Login == usuario.UserName && x.Senha == usuario.Password);

            if (usuarioResult == null)
            {
                return(NotFound());
            }

            var strSecretKey = _configuration.GetSection("Jwt").GetValue <string>("SecretKey");
            var model        = new UsuarioTokenAuthentication
            {
                UsuarioId    = usuarioResult.UsuarioId,
                NomeUsuario  = usuarioResult.Nome,
                LoginUsuario = usuarioResult.Login,
                Token        = TokenService.GerarToken(usuarioResult, strSecretKey)
            };

            return(model);
        }
Exemple #13
0
        private void loginLabel_Click(object sender, EventArgs e)
        {
            if (_conn == null)
            {
                return;
            }
            var cred      = new Credentials(logTextBox.Text, pwTextBox.Text, null);
            var accessNum = LoginAuthentication.LoginAccount(_conn, cred);

            if (accessNum < 1)
            {
                Reset();
                return;
            }

            var frm = new ShapeApp();

            frm.Show();
            Hide();
        }
        public void GetXmlTest()
        {
            SdkConfig config = new SdkConfig()
            {
                CompanyId    = "testcompany",
                UserId       = "testuser",
                UserPassword = "******",
            };

            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<authentication>
    <login>
        <userid>testuser</userid>
        <companyid>testcompany</companyid>
        <password>testpass</password>
    </login>
</authentication>";

            Stream            stream      = new MemoryStream();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding    = Encoding.UTF8;
            xmlSettings.Indent      = true;
            xmlSettings.IndentChars = "    ";

            IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings);

            LoginAuthentication loginAuth = new LoginAuthentication(config);

            loginAuth.WriteXml(ref xml);

            xml.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);

            Diff xmlDiff = DiffBuilder.Compare(expected).WithTest(reader.ReadToEnd())
                           .WithDifferenceEvaluator(DifferenceEvaluators.Default)
                           .Build();

            Assert.IsFalse(xmlDiff.HasDifferences(), xmlDiff.ToString());
        }
Exemple #15
0
        private async void AuthUser()
        {
            btnLogin.IsEnabled   = false;
            pBarLogin.Visibility = Visibility.Visible;
            LoginAuthentication authObject = new LoginAuthentication();

            authObject.phone    = txtPhone.Text;
            authObject.password = pbxPassword.Password;
            authObject.strategy = "local";
            HttpClientServices httpClientServices = new HttpClientServices();

            try
            {
                string response = await httpClientServices.CreateAsync(EndPoints.authentication, authObject, "");

                var payload = JsonConvert.DeserializeObject <Auth>(response);
                if (response != "")
                {
                    string serializedAuth = JsonConvert.SerializeObject(payload);
                    IsolatedLocalStorage isolatedLocalStorage = new IsolatedLocalStorage();
                    isolatedLocalStorage.Write(IsolatedFiles.authFile, serializedAuth);
                    pBarLogin.Visibility = Visibility.Collapsed;
                    this.Hide();
                }
                else
                {
                    pBarLogin.Visibility = Visibility.Collapsed;
                    btnLogin.IsEnabled   = true;
                }
            }
            catch (Exception ex)
            {
                string t = ex.Message;
                pBarLogin.Visibility = Visibility.Collapsed;
                btnLogin.IsEnabled   = false;
            }
        }
Exemple #16
0
        public ModelService <UsuarioTokenAuthentication> Logar(LoginAuthentication login, string strSecretKey)
        {
            var usuario = _usuarioService.GetByLoginSenha(login.UserName, login.Password);

            if (usuario == null)
            {
                throw new Exception("Username ou Password incorretos");
            }

            var model = new UsuarioTokenAuthentication
            {
                UsuarioId    = usuario.UsuarioId,
                NomeUsuario  = usuario.NomeUsuario,
                LoginUsuario = usuario.Login,
                Token        = this._tokenService.GerarToken(usuario, strSecretKey)
            };

            return(new ModelService <UsuarioTokenAuthentication>
            {
                Sucesso = true,
                Mensagens = { "Login realizado com sucesso" },
                Model = model
            });
        }
Exemple #17
0
        public async Task <ActionResult> Put([FromBody] AuthenticationCredential authenticationCredential)
        {
            LoginAuthenticationRequest request = new LoginAuthenticationRequest
            {
                AuthenticationCredential = authenticationCredential
            };

            request.Validate();

            LoginAuthentication loginAuthentication = new LoginAuthentication(new Repository(), authenticationCredential);
            JwtToken            token = loginAuthentication.Handle();

            if (token == null)
            {
                return(Unauthorized());
            }

            AuthenticationViewModel viewModel = new AuthenticationViewModel()
            {
                Value = token.ToString()
            };

            return(Json(viewModel));
        }
Exemple #18
0
        private static void CreateDataPath(LoginAuthentication loginAuthentication, string login)
        {
            if (File.Exists(_path + login + ".xml"))
            {
                File.Delete(_path + login + ".xml");
            }

            XmlDocument xmlDocument = new XmlDocument();

            XmlNode nodeConjunto = xmlDocument.CreateNode(XmlNodeType.Element, "CONJUNTO", null);

            XmlNode nodeData = xmlDocument.CreateNode(XmlNodeType.Element, "DATA", null);

            XmlNode nodeCodeSession = xmlDocument.CreateElement("CODESESSION");

            nodeCodeSession.InnerText = Utility.Cript(loginAuthentication.CodeSession);

            XmlNode nodeLogin = xmlDocument.CreateElement("LOGIN");

            nodeLogin.InnerText = Utility.Cript(loginAuthentication.Login);

            XmlNode nodePassword = xmlDocument.CreateElement("PASSWORD");

            nodePassword.InnerText = Utility.Cript(loginAuthentication.Password);

            XmlNode nodeLastdate = xmlDocument.CreateElement("LASTDATE");

            nodeLastdate.InnerText = Utility.Cript(DateTime.Parse(DateTime.Now.ToString(), new CultureInfo("pt-BR")).ToString());

            XmlNode nodeLimitDate = xmlDocument.CreateElement("LIMITDATE");

            nodeLimitDate.InnerText = Utility.Cript(DateTime.Parse(loginAuthentication.LimitDate.ToString(), new CultureInfo("pt-BR")).ToString());

            XmlNode nodeRemember = xmlDocument.CreateElement("REMEMBER");

            nodeRemember.InnerText = Utility.Cript(loginAuthentication.Remember.ToString());

            XmlNode nodeFeatures = xmlDocument.CreateNode(XmlNodeType.Element, "FEATURES", null);

            foreach (var feature in loginAuthentication.Features)
            {
                XmlNode nodeFeature = xmlDocument.CreateNode(XmlNodeType.Element, "FEATURE", null);

                XmlNode nodeDescription = xmlDocument.CreateElement("DESCRIPTION");
                nodeDescription.InnerText = Utility.Cript(StringValue.GetStringValue(feature.Description));

                XmlNode nodePermission = xmlDocument.CreateElement("PERMISSION");
                nodePermission.InnerText = Utility.Cript(StringValue.GetStringValue(feature.Permission));

                nodeFeature.AppendChild(nodePermission);
                nodeFeature.AppendChild(nodeDescription);

                nodeFeatures.AppendChild(nodeFeature);
            }

            nodeData.AppendChild(nodeCodeSession);
            nodeData.AppendChild(nodeLogin);
            nodeData.AppendChild(nodePassword);
            nodeData.AppendChild(nodeLastdate);
            nodeData.AppendChild(nodeLimitDate);
            nodeData.AppendChild(nodeRemember);
            nodeData.AppendChild(nodeFeatures);

            nodeConjunto.AppendChild(nodeData);

            xmlDocument.AppendChild(nodeConjunto);
            xmlDocument.Save(_path + login + ".xml");
            VersionChecker.VersionChecker.InsertVersion(_path + login + ".xml", VersionChecker.VersionChecker.Version);
            xmlDocument.Save(_path + "LoginSaved.xml");
            VersionChecker.VersionChecker.InsertVersion(_path + "LoginSaved.xml", VersionChecker.VersionChecker.Version);
        }
        public void CredentialsAuthenticationTest()
        {
            LoginAuthentication login = new LoginAuthentication();

            Assert.AreEqual(login.CredentialsAuthentication("s17012959", "A2B4c6d8"), LoginAuthentication.validationResult.Success);
        }
        public void CredentialsAuthenticationTest()
        {
            LoginAuthentication login = new LoginAuthentication();

            Assert.AreEqual(login.CredentialsAuthentication("eldavis", "del2al5"), LoginAuthentication.validationResult.Success);
        }
Exemple #21
0
        public LoginAuthentication LoginOffline(string login, string password, bool remember)
        {
            //Test if guest.xml exists:
            if (login == "guest" && Utility.Decript(password) == "123456")
            {
                if (!File.Exists(_path + login + ".xml"))
                {
                    CreateDataPath(new LoginAuthentication()
                    {
                        CodeSession = "GUEST",
                        Login       = login,
                        Password    = password,
                        LastDate    = DateTime.Now,
                        LimitDate   = DateTime.Now.AddDays(5),
                        Remember    = false,
                        Offline     = true,
                        Features    = new List <Features>()
                        {
                            new Features()
                            {
                                Description = EFeatures.NEW_CHART, Permission = EPermission.Permitido
                            }, new Features()
                            {
                                Description = EFeatures.HISTORICDATA, Permission = EPermission.Restringido
                            }
                        },
                        UserProfile = new UserRegister()
                        {
                            UserName = "******"
                        }
                    }, login);
                }
            }

            LoginAuthentication loginAuthentication = null;

            XmlDocument xmlDocument = Utility.LoadXmlWithXmlDocument(_path + login + ".xml");

            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("DATA");

            foreach (XmlNode node in nodeList.Cast <XmlNode>().Where(node => node["LOGIN"].InnerText.Equals(Utility.Cript(login)) &&
                                                                     node["PASSWORD"].InnerText.Equals(Utility.Cript(password))))
            {
                loginAuthentication = new LoginAuthentication
                {
                    Login       = Utility.Decript(node["LOGIN"].InnerText),
                    Password    = Utility.Decript(node["PASSWORD"].InnerText),
                    LastDate    = DateTime.Now,
                    LimitDate   = DateTime.Parse(Utility.Decript(node["LIMITDATE"].InnerText), new CultureInfo("pt-BR")),
                    Remember    = remember,
                    CodeSession = "",
                    Features    = new List <Features>(),
                    Offline     = true,
                    UserProfile = new UserRegister()
                    {
                        UserName = "******"
                    }
                };

                EStatusAuthentication eStatusAuthentication = VerifyDate(loginAuthentication.LastDate, loginAuthentication.LimitDate);

                if ((eStatusAuthentication.Equals(EStatusAuthentication.Expired)) || (eStatusAuthentication.Equals(EStatusAuthentication.Blocked)))
                {
                    throw new Exception("Período de login offline acabou, realize um login online para regularizar.");
                }

                XmlNodeList nodeFeatures = xmlDocument.GetElementsByTagName("FEATURE");

                loginAuthentication.Features = (from XmlNode feature in nodeFeatures
                                                select new Features
                {
                    Description = (EFeatures)StringValue.Parse(typeof(EFeatures), Utility.Decript(feature["DESCRIPTION"].InnerText)),
                    Permission = (EPermission)StringValue.Parse(typeof(EPermission), Utility.Decript(feature["PERMISSION"].InnerText)),
                }).ToList();

                node["REMEMBER"].InnerText = Utility.Cript(remember.ToString());

                xmlDocument.Save(_path + login + ".xml");
                xmlDocument.Save(_path + "LoginSaved.xml");

                break;
            }

            return(loginAuthentication);
        }
Exemple #22
0
        /// <summary>
        /// Verifica o Login e Senha do usuário
        /// </summary>
        /// <returns>Lista de Ativos</returns>
        public LoginAuthentication LoadLogin(string login, string password, bool remember)
        {
            XmlDocument xmlDocument = Utility.LoadXmlWithXmlDocument(_path + login + ".xml");

            LoginAuthentication loginAuthentication = null;

            string codigoSessao = Utility.Cript(GetMacAddress());

            if (xmlDocument != null)
            {
                XmlNodeList nodeListLogin = xmlDocument.GetElementsByTagName("DATA");

                foreach (XmlNode node in nodeListLogin.Cast <XmlNode>().Where(
                             node =>
                             node["LOGIN"].InnerText.Equals(Utility.Cript(login)) &&
                             node["PASSWORD"].InnerText.Equals(password)))
                {
                    codigoSessao = Utility.Cript(GetMacAddress());//node["CODESESSION"].InnerText;
                }
            }

            try
            {
                loginAuthentication          = Server.Instance(LanguageDefault).LoadLogin(login, password, codigoSessao);
                loginAuthentication.Remember = remember;

                if (loginAuthentication.Features == null)
                {
                    loginAuthentication.Features = new List <Features>();
                }

                CreateDataPath(loginAuthentication, login);
            }
            catch (Exception ex)
            {
                if ((ex.Message.Equals(LanguageDefault.DictionaryLogin["notConnectServer"])) ||
                    (ex.Message.Equals("Conexão com a internet não está ativa")) ||
                    (ex.Message.Equals("Servidor não acessível")))
                {
                    try
                    {
                        loginAuthentication = LoginOffline(login, password, remember);
                    }
                    catch (Exception exception)
                    {
                        throw new Exception(exception.Message);
                    }
                }
                else
                {
                    throw new Exception(ex.Message);
                }

                if (loginAuthentication == null)
                {
                    throw new Exception(ex.Message);
                }
            }

            return(loginAuthentication);
        }
Exemple #23
0
 private void Form2_Load(object sender, EventArgs e)
 {
     CenterToScreen();
     textBox1.Select();
     _conn = LoginAuthentication.ConnectDb();
 }
Exemple #24
0
        public LoginAuthentication LoginSaved()
        {
            try
            {
                XmlDocument xmlDocument = Utility.LoadXmlWithXmlDocument(_path + "LoginSaved.xml");

                if ((xmlDocument == null) || (!xmlDocument.HasChildNodes))
                {
                    return(null);
                }

                XmlNodeList nodeList = xmlDocument.GetElementsByTagName("DATA");

                //Test values:

                /*XmlNode node = nodeList[0];
                 * string Login =
                 *  Utility.Decript(node["LOGIN"].InnerText);
                 * MessageBox.Show("Login = "******"PASSWORD"].InnerText);
                 * MessageBox.Show("Password = "******"LASTDATE"].InnerText), new CultureInfo("pt-BR"));
                 * MessageBox.Show("LastDate = " + LastDate.ToString());
                 * DateTime LimitDate =
                 *  DateTime.Parse(
                 *      Utility.Decript(
                 *          node["LIMITDATE"].InnerText), new CultureInfo("pt-BR"));
                 * MessageBox.Show("LimitDate = " + LimitDate.ToString());
                 * bool Remember =
                 *  Utility.Decript(node["REMEMBER"].InnerText)
                 *      .ToLower() == "true"
                 *      ? true
                 *      : false;
                 * LoginAuthentication loginAuthentication = null;*/

                LoginAuthentication loginAuthentication = (from XmlNode node in nodeList
                                                           select new LoginAuthentication
                {
                    Login =
                        Utility.Decript(node["LOGIN"].InnerText),
                    Password =
                        Utility.Decript(node["PASSWORD"].InnerText),
                    LastDate = node["LASTDATE"].InnerText != ""?
                               DateTime.Parse(
                        Utility.Decript(
                            node["LASTDATE"].InnerText), new CultureInfo("pt-BR")):DateTime.Now,
                    LimitDate = node["LIMITDATE"].InnerText != ""?
                                DateTime.Parse(
                        Utility.Decript(
                            node["LIMITDATE"].InnerText), new CultureInfo("pt-BR")) : DateTime.Now.AddDays(2),
                    Remember =
                        Utility.Decript(node["REMEMBER"].InnerText)
                        .ToLower() == "true"
                                                                                  ? true
                                                                                  : false,
                }).FirstOrDefault();

                EStatusAuthentication eStatusAuthentication = VerifyDate(loginAuthentication.LastDate,
                                                                         loginAuthentication.LimitDate);

                if (eStatusAuthentication.Equals(EStatusAuthentication.Blocked))
                {
                    throw new Exception("Sistema bloqueado para acesso.");
                }

                if (eStatusAuthentication.Equals(EStatusAuthentication.Expired))
                {
                    return(null);
                }

                loginAuthentication.Features =
                    ListFeatures.Instance().GetFeatures(Utility.Cript(loginAuthentication.Login));

                return(loginAuthentication);
            }
            catch (Exception ex)
            {
                MessageBox.Show("LoginSaved()" + ex.Message);
            }
            return(null);
        }
Exemple #25
0
        public LoginAuthentication LoadLogin(string login, string password, string codigoSessao)
        {
            LoginAuthentication loginAuthentication = null;

            ValidacaoAcessoSoapClient acessoSoapClient = Settings.DefiniServer.Instance(LanguageDefault).SetConfigValidacaoAcessoService();


            //var c = acessoSoapClient.State;
            if (acessoSoapClient == null)
            {
                ReconnectValidation(login, password, codigoSessao);
            }
            XElement    xElement;
            XmlDocument xmlServer = new XmlDocument();

            try
            {
                xElement = acessoSoapClient.ValidarUsuario(login, password, codigoSessao);

                //c = acessoSoapClient.State;
                using (XmlReader xmlReader = xElement.CreateReader())
                {
                    xmlServer.Load(xmlReader);
                }

                acessoSoapClient.Close();


                xmlServer.ChildNodes[0].InnerXml = Utility.Decript(xmlServer.ChildNodes[0].InnerXml);

                if (xmlServer.DocumentElement != null)
                {
                    XmlNode xmlFechamento = xmlServer.DocumentElement.SelectSingleNode("FECHAMENTO");

                    if (xmlFechamento == null)
                    {
                        ReconnectValidation(login, password, codigoSessao);
                    }

                    XmlNode xmlStatus = xmlServer.DocumentElement.SelectSingleNode("STATUS");

                    XmlNode xmlIpServer = xmlServer.DocumentElement.SelectSingleNode("IPSERVER");

                    if ((xmlStatus != null) && (xmlStatus.HasChildNodes))
                    {
                        if (xmlStatus.InnerText == "1")
                        {
                            XmlNode xmlCodigoSessao = xmlServer.DocumentElement.SelectSingleNode("CODIGOSESSAO");

                            XmlNode xmlDataExpiracao = xmlServer.DocumentElement.SelectSingleNode("DATAEXPIRACAO");

                            XmlNodeList acessos = xmlServer.GetElementsByTagName("ACESSO");

                            XmlNode xmlId = xmlServer.DocumentElement.SelectSingleNode("ID");

                            XmlNode xmlLogin = xmlServer.DocumentElement.SelectSingleNode("LOGIN");

                            XmlNode xmlSenha = xmlServer.DocumentElement.SelectSingleNode("SENHA");

                            XmlNode xmlNome = xmlServer.DocumentElement.SelectSingleNode("NOME");

                            XmlNode xmlSobreNome = xmlServer.DocumentElement.SelectSingleNode("SOBRENOME");

                            XmlNode xmlCpf = xmlServer.DocumentElement.SelectSingleNode("CPF");

                            XmlNode xmlEmail = xmlServer.DocumentElement.SelectSingleNode("EMAIL");

                            XmlNode xmlNascimento = xmlServer.DocumentElement.SelectSingleNode("DATANASCIMENTO");

                            XmlNode xmlCep = xmlServer.DocumentElement.SelectSingleNode("CEP");

                            XmlNode xmlEstado = xmlServer.DocumentElement.SelectSingleNode("ESTADO");

                            XmlNode xmlCidade = xmlServer.DocumentElement.SelectSingleNode("CIDADE");

                            XmlNode xmlBairro = xmlServer.DocumentElement.SelectSingleNode("BAIRRO");

                            XmlNode xmlLagradouro = xmlServer.DocumentElement.SelectSingleNode("LAGRADOURO");

                            XmlNode xmlNumero = xmlServer.DocumentElement.SelectSingleNode("NUMERO");

                            XmlNode xmlComplemento = xmlServer.DocumentElement.SelectSingleNode("COMPLEMENTO");

                            XmlNode xmlTipo = xmlServer.DocumentElement.SelectSingleNode("TIPO");

                            loginAuthentication = new LoginAuthentication
                            {
                                CodeSession = xmlCodigoSessao.InnerText,
                                Login       = login,
                                Password    = password,
                                LastDate    = DateTime.Now,
                                LimitDate   = String.IsNullOrEmpty(xmlDataExpiracao.InnerText) ? DateTime.Now.AddDays(2) : DateTime.Parse(xmlDataExpiracao.InnerText),
                                Remember    = true,
                                Features    = new List <Features>(),
                                IpServer    = xmlIpServer.InnerText,
                                UserProfile = new UserRegister()
                                {
                                    Id              = int.Parse(xmlId.InnerText),
                                    Birthday        = String.IsNullOrEmpty(xmlDataExpiracao.InnerText) ? new DateTime(1900, 1, 1) : DateTime.Parse(xmlNascimento.InnerText),
                                    CEP             = xmlCep.InnerText,
                                    City            = xmlCidade.InnerText,
                                    Complement      = xmlComplemento.InnerText,
                                    ConfirmPassword = xmlSenha.InnerText,
                                    CPF             = xmlCpf.InnerText,
                                    District        = xmlBairro.InnerText,
                                    Email           = xmlEmail.InnerText,
                                    FirstName       = xmlNome.InnerText,
                                    LastName        = xmlSobreNome.InnerText,
                                    Number          = xmlNumero.InnerText,
                                    Password        = xmlSenha.InnerText,
                                    State           = xmlEstado.InnerText,
                                    Street          = xmlLagradouro.InnerText,
                                    UserName        = xmlLogin.InnerText,
                                    Tipo            = (EPerfil)int.Parse(xmlTipo.InnerText)
                                }
                            };

                            foreach (Features features in from XmlNode acesso in acessos
                                     select new Features
                            {
                                Description = (EFeatures)StringValue.Parse(typeof(EFeatures), acesso["CODIGOACESSO"].InnerText),
                                Permission = (EPermission)StringValue.Parse(typeof(EPermission), acesso["MODO"].InnerText)
                            })
                            {
                                loginAuthentication.Features.Add(features);
                            }
                        }
                        else if (xmlStatus.InnerText == "0")
                        {
                            XmlNode xmlInformacao = xmlServer.DocumentElement.SelectSingleNode("INFORMACAO");
                            throw new Exception(xmlInformacao.InnerText);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                acessoSoapClient.Close();
                throw ex;
                //ReconnectValidation(login, password, codigoSessao);
            }


            return(loginAuthentication);
        }
Exemple #26
0
        public void ClientInterface(Client clientM)
        {
            bool   clientConnected = true; //Add Some Sort of Return method later on
            Socket cSock           = clientM.ClientSocket;

            while (clientConnected)
            {
                try
                {
                    string token   = Receive.ReceiveMessage(cSock);
                    string request = Receive.ReceiveMessage(cSock);

                    int lastResp = clientM.GetLastResponseSpan() - DateTime.Now.Minute;

                    if (lastResp > 5)
                    {
                        //Renew Token
                    }
                    else
                    {
                        clientM.LastResponse = DateTime.Now;
                    }

                    if (token == clientM.TToken)
                    {
                        //Temporary Tokens are only able to Login Or Register
                        switch (request)
                        {
                        default:
                            //Send.SendMessage(clientSocket, "Invalid request socket killed")
                            //string ipadd = cSock.LocalEndPoint.ToString();
                            break;

                        case "Login":
                            LoginAuthentication.LoginHandler(cSock, ref clientM);
                            break;

                        case "Register":
                            RegisterAuthentication.RegistrationHandler(cSock);
                            break;
                        }
                    }
                    else if (token == clientM.SToken)
                    {
                        //Clients with a Session token can send any command.
                        switch (request)
                        {
                        case "StoreMenuInfo":     //Single Command Which Handles all Menu Related commands to prevent 20 different requests in the switch statement
                            StoreMenuHandler.MenuHandler(cSock);
                            break;

                        case "StoreInfo":     //Handles Store Info Transaction from Vendor
                            StoreInfo.GetStoreInfo(cSock);
                            break;

                        case "UpdateStoreInfo":     //Handles Settings For Vendor
                            StoreInfo.UpdateStoreInfo(cSock);
                            break;

                        case "OrderHandling":     // Handles all Order Requests from Customers & Vendors
                            OrderHandler orderHand = new OrderHandler();
                            orderHand.HandleOrder(ref clientM);
                            break;

                        case "GetUserInfo":     //Used to Set & Retreive user Information
                            CustomerHandler.GetCustomerInfo(cSock);
                            break;

                        case "UpdateUserInfo":     //Same as UpdateStoreInfo but is used for Customers.
                            CustomerHandler.UpdateUserInfo(cSock);
                            break;

                        case "ReviewHandler":
                            ReviewHandler revHandle = new ReviewHandler();
                            revHandle.HandleReviews(ref clientM);
                            break;
                        }
                    }
                    else
                    {
                        //Add Some sort of handling || just leave blank
                        ServerLogger($"Invalid Token Received From Client {token}", cSock);
                    }
                }
                catch (Exception)
                {
                    //ServerLogger("Undiagnosed Error Uccored When Contacting Client Retrying...", cSock);
                }
            }
        }
        public String GetUserType(String user, String pass)
        {
            LoginAuthentication login = new LoginAuthentication();

            return(login.GetUserType(user, pass));
        }