Пример #1
0
        public int BAaddLoginDetails(LoginEntities objLoginDetails)
        {
            DALogin objaddLoginDA = new DALogin();
            int     returnValue   = objaddLoginDA.DAaddLoginDetails(objLoginDetails);

            return(returnValue);
        }
Пример #2
0
        public ActionResult Login(LoginDetails loginDetails)
        {
            using (var db = new LoginEntities())
            {
                var UserName1  = loginDetails.UserName1;
                var Passsword1 = loginDetails.Password1;

                if (db.LoginDetails.Any(x => x.UserName1.Equals(loginDetails.UserName1, StringComparison.Ordinal) && x.Password1.Equals(loginDetails.Password1, StringComparison.Ordinal)))
                {
                    var user = db.LoginDetails.Where(a => a.UserName1.Equals(loginDetails.UserName1) && a.Password1.Equals(loginDetails.Password1)).FirstOrDefault();
                    if (user != null)
                    {
                        Session["UserName"]            = user.UserName1;
                        Session["Password"]            = user.Password1;
                        Session["TransactionPassword"] = user.TransactionPassword;
                        Session["UserRole"]            = user.UserRole;
                        Session["CustomerName"]        = user.CustomerName;
                        Session["AccountNumber"]       = user.AccountNumber1;

                        return(RedirectToAction("UserDashBoard"));
                    }
                    else
                    {
                        return(View());
                    }
                }
            }

            ModelState.AddModelError("", "Invalid email and password");
            return(View());
        }
Пример #3
0
        public ActionResult Login(tblLogin model, string returnUrl)
        {
            LoginEntities db       = new LoginEntities();
            var           dataItem = db.tblLogins.Where(x => x.username == model.username && x.password == model.password).First();

            if (dataItem != null)
            {
                FormsAuthentication.SetAuthCookie(dataItem.username, false);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    if (dataItem.role == "Admin")
                    {
                        return(RedirectToAction("Dashboard"));
                    }
                    else
                    {
                        return(RedirectToAction("Index"));
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid user/pass");
                return(View());
            }
        }
Пример #4
0
        public static string deletarPessoa(pessoa p)
        {
            using (LoginEntities entities = new LoginEntities())
            {
                try
                {
                    pessoa deletePessoa = new pessoa();
                    deletePessoa = entities.pessoas.FirstOrDefault(del => del.cpf == p.cpf);

                    if (deletePessoa == null || deletePessoa.cpf.Equals(null) || deletePessoa.cpf.Equals(""))
                    {
                        return("Operação não realizada.\nNão foi encontrado ninguém com este CPF na base de dados!");
                    }
                    else
                    {
                        entities.pessoas.Remove(deletePessoa);
                        entities.SaveChanges();
                        return("Operação realizada com sucesso!\nSua conta foi apagada da base de dados.");
                    }
                }
                catch (Exception e)
                {
                    return("Erro: " + e.Message);
                }
            }
        }
Пример #5
0
        public ActionResult login(Login Log)
        {
            using (LoginEntities loginmodel = new LoginEntities())
            {
                if (loginmodel.Logins.Any(x => x.UserName == Log.UserName) && loginmodel.Logins.Any(x => x.Password == Log.Password))
                {
                    return(RedirectToAction("Index", "Home"));
                }

                var d = loginmodel.Logins.Where(x => x.UserName == Log.UserName);//  .Any(x => x.UserName != Log.UserName);


                if (d.Count() == 0)
                {
                    ViewBag.Dublicate = "Wrong Username";
                    return(View("login", Log));
                }
                //else if (loginmodel.Logins.Any(x => x.UserName != Log.UserName))
                //{
                //    ViewBag.Dublicate = "Wrong Username";
                //    return View("login", Log);
                //}
                if (loginmodel.Logins.Any(x => x.Password != Log.Password))
                {
                    ViewBag.SuccessMessage = "Wrong Password";
                    return(View("login", Log));
                }
                else
                {
                    return(View("login", Log));
                }
            }
        }
Пример #6
0
        public object Post([FromBody] User UserModel)
        {
            string token    = "";
            User   Userinfo = new User();

            using (LoginEntities db = new LoginEntities())
            {
                Userinfo = db.Users.Where(x => x.Account_name == UserModel.Account_name &&
                                          x.Password == UserModel.Password).SingleOrDefault <User>();
            };
            if (Userinfo == null)
            {
                UserModel.LoginErrorMessage = "Incorrect Username and password ";
                // return View("Index", UserModel);
                token = "Incorrect Username and password";
                //System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
            }
            else
            {
                //Session["UserAccount"] = UserModel.Account_name;
                token = "successfully logged in";
                System.Web.HttpContext.Current.Response.AppendHeader("Status", "Successfully");
                //System.Web.HttpContext.Current.Response.Redirect("~/Home/Index");
            }
            return(token);
        }
Пример #7
0
 public JsonResult GetData()
 {
     using (LoginEntities db = new LoginEntities())
     {
         List <Student> employeeList = db.Students.ToList <Student>();
         return(Json(new { data = employeeList }, JsonRequestBehavior.AllowGet));
     }
 }
Пример #8
0
        public ActionResult Manage(LoginEntities loginEntities)
        {
            AspNetUser aspNetUserUpdate = new AspNetUser();

            using (var userContext = new ZiorEntities()) //made connection with DbContext and check if user exist then update data in database
            {
                aspNetUserUpdate.Email    = loginEntities.Email;
                aspNetUserUpdate.Password = loginEntities.Password;
                userContext.SaveChanges();
            }
            return(View());
        }
Пример #9
0
        public void Insert(LoginEntities loginEntities)
        {
            connection = new SqlConnection(ConnectionString(cs));
            var        Query = "INSERT INTO Login(Username,Password,Email) VALUES(@Username,@Password,@Email)";
            SqlCommand com   = new SqlCommand(Query, connection);

            com.CommandType = CommandType.Text;
            com.Parameters.Add("@Username", SqlDbType.VarChar).Value = loginEntities.Username;
            com.Parameters.Add("@Password", SqlDbType.VarChar).Value = loginEntities.Password;
            com.Parameters.Add("@Email", SqlDbType.VarChar).Value    = "";
            connection.Open();
            com.ExecuteNonQuery();
            connection.Close();
            connection.Dispose();
        }
Пример #10
0
        public ActionResult Login(LoginEntities loginEntities)
        {
            using (var userContext = new ZiorEntities()) //made connection with DbContext and check if user exist in database on not
            {
                bool isValid = userContext.AspNetUsers.Any(user => user.Email == loginEntities.Email && user.Password == loginEntities.Password);
                if (isValid)
                {
                    FormsAuthentication.SetAuthCookie(loginEntities.Email, false); // Persistant cookie (true to create a persistant cookie (one that saved across browser sessions) otherwise false) works on remember checkbox
                    return(RedirectToAction("Index", "User"));
                }

                ModelState.AddModelError("", "Invalid username and password. Try again!!!!!");
            }
            return(View());
        }
Пример #11
0
        public ActionResult Login(LoginEntities loginEntities)
        {
            using (var userContext = new ZiorEntities()) //made connection with DbContext and check if user exist in database on not
            {
                bool isValid = userContext.AspNetUsers.Any(user => user.Email == loginEntities.Email && user.Password == loginEntities.Password);
                if (isValid)
                {
                    FormsAuthentication.SetAuthCookie(loginEntities.Email, false);
                    return(RedirectToAction("Index", "User"));
                }

                ModelState.AddModelError("", "Invalid username and password. Try again!!!!!");
            }
            return(View());
        }
Пример #12
0
 public ActionResult Register(User userModel)
 {
     try
     {
         using (LoginEntities db = new LoginEntities())
         {
             db.Users.Add(userModel);
             db.SaveChanges();
         }
     }
     catch (Exception)
     {
         throw;
     }
     return(RedirectToAction("Index", "Login"));
 }
Пример #13
0
        public string Get(User UserModel)
        {
            string Status = null;
            string header = "" /*HttpRequestHeader("Authorization")*/;

            using (LoginEntities db = new LoginEntities())
                if (header == "Incorrect Username and password")
                {
                    Status = "Chua dang nhap thanh cong";
                }
                else
                {
                    Status = UserModel.Account_name;
                }
            return(Status);
        }
Пример #14
0
 public static pessoa buscarPessoa(string cpf)
 {
     using (LoginEntities entities = new LoginEntities())
     {
         try
         {
             pessoa pessoaEncontrada = new pessoa();
             pessoaEncontrada = entities.pessoas.FirstOrDefault(find => find.cpf == cpf);
             return(pessoaEncontrada);
         }
         catch (Exception e)
         {
             return(null);
         }
     }
 }
Пример #15
0
        public ActionResult AddorEdit(Login login)
        {
            using (LoginEntities loginmodel = new LoginEntities())
            {
                if (loginmodel.Logins.Any(x => x.UserName == login.UserName))
                {
                    ViewBag.Dublicate = "User name found ";
                    return(View("AddorEdit", login));
                }

                loginmodel.Logins.Add(login);
                loginmodel.SaveChanges();
            }
            ModelState.Clear();
            ViewBag.SuccessMessage = "Registration succesfull";
            return(View("AddorEdit", new Login()));
        }
 public ActionResult Login(UserLogin objuser)
 {
     if (ModelState.IsValid)
     {
         using (LoginEntities DB = new LoginEntities())
         {
             var obj = DB.UserLogins.Where(a => a.Username.Equals(objuser.Username) && a.Password.Equals(objuser.Password)).FirstOrDefault();
             if (obj != null)
             {
                 Session["UserID"]   = obj.UserID.ToString();
                 Session["UserName"] = obj.Username.ToString();
                 return(RedirectToAction("UserDashBoard"));
             }
         }
     }
     return(View(objuser));
 }
Пример #17
0
        public string Register(RegistrationDetails RegUser)
        {
            string Response = "Registered";

            try
            {
                using (LoginEntities ent = new LoginEntities())
                {
                    var query = (from u in ent.UserDetails
                                 where u.UserID == RegUser.UserID
                                 select u.UserID).Count();
                    if (query > 0)
                    {
                        Response = "User name already exists";
                    }
                    else
                    {
                        UserDetail user = new UserDetail()
                        {
                            FirstName   = RegUser.FirstName,
                            LastName    = RegUser.LastName,
                            UserID      = RegUser.UserID,
                            Password    = RegUser.Password,
                            PhoneNumber = RegUser.PhoneNumber,
                            EmailID     = RegUser.EmailID
                        };

                        ent.UserDetails.Add(user);
                        if (ent.SaveChanges() > 0)
                        {
                            Response = "Registered";
                        }
                        else
                        {
                            Response = "Failed to Register";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(Response);
        }
Пример #18
0
 public ActionResult Authorize(app.Models.Usuario userModel)
 {
     using (LoginEntities db = new LoginEntities())
     {
         var userDetails = db.Usuario.Where(x => x.nombreus == userModel.nombreus && x.pass == userModel.pass).FirstOrDefault();
         if (userDetails == null)
         {
             userModel.LoginErrorMessage = "Wrong username or password.";
             return(View("Index", userModel));
         }
         else
         {
             Session["userID"]   = userDetails.usuarioId;
             Session["userName"] = userDetails.nombreus;
             return(RedirectToAction("Index", "Home"));
         }
     }
 }
Пример #19
0
 public ActionResult Autherize(User userModel)
 {
     using (LoginEntities db = new LoginEntities())
     {
         var userDetails = db.Users.Where(x => x.Username == userModel.Username && x.Password == userModel.Password).FirstOrDefault();
         if (userDetails == null)
         {
             userModel.LoginErrorMessage = "Wrong username or password.";
             return(View("Index", userModel));
         }
         else
         {
             Session["userID"]   = userDetails.UserID;
             Session["userName"] = userDetails.Username;
             return(RedirectToAction("Index", "Home"));
         }
     }
 }
Пример #20
0
        public ActionResult CheckTransactionPassword(LoginDetails loginDetails)
        {
            using (var db = new LoginEntities())
            {
                if (Session["TransactionPassword"].ToString().Equals(loginDetails.TransactionPassword))
                {
                    var user = db.LoginDetails.Where(a => a.TransactionPassword.Equals(Session["TransactionPassword"].ToString())).Distinct();
                    if (user != null)
                    {
                        return(RedirectToAction("Transfer"));
                    }
                    else
                    {
                        return(View());
                    }
                }
            }

            ModelState.AddModelError("", "Invalid email and password");
            return(View());
        }
Пример #21
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            LoginEntities objLoginDetails = new LoginEntities();


            objLoginDetails.UserName = UserName.Text;
            objLoginDetails.Password = Password.Text;

            //BAL
            BALogin objLoginBA = new BALogin();
            int     rValue     = objLoginBA.BAaddLoginDetails(objLoginDetails);

            if (rValue > 0)
            {
                Response.Redirect("Category.aspx");
            }
            else
            {
                Response.Write("<script>alert('UserName or Password not matched');</script>");
            }
        }
        public HttpResponseMessage lista(LoginEntities model)
        {
            var HttpResponse = new HttpResponseMessage();

            try
            {
                response.Code    = HttpStatusCode.OK;
                response.Message = "Success";
                response.Result  = context.Location.Where(x => x.State == ConstantHelper.Status.ACTIVE).Select(x => x.Name).ToList();

                HttpResponse         = new HttpResponseMessage(HttpStatusCode.OK);
                HttpResponse.Content = new StringContent(JsonConvert.SerializeObject(response));
                HttpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return(HttpResponse);
            }
            catch
            {
                HttpResponse = new HttpResponseMessage(HttpStatusCode.Conflict);
                return(HttpResponse);
            }
        }
Пример #23
0
        public string Login(UserLoginDetails loginDetails)
        {
            string Response = "Logged in successfully";

            try
            {
                using (LoginEntities ent = new LoginEntities())
                {
                    var CheckUser = (from user in ent.UserDetails
                                     where loginDetails.UserID == user.UserID
                                     select user.UserID
                                     ).Count();
                    if (CheckUser == 0)
                    {
                        Response = "User Doesn't exist";
                    }
                    else
                    {
                        var VerifyPwd = (from user in ent.UserDetails
                                         where loginDetails.UserID == user.UserID
                                         select user.Password
                                         ).FirstOrDefault().ToString();
                        if (VerifyPwd == loginDetails.Password)
                        {
                            Response = "Logged in successfully";
                        }
                        else
                        {
                            Response = "Password Doesn't match";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(Response);
        }
Пример #24
0
        public int DAaddLoginDetails(LoginEntities objLoginDetails)
        {
            int val = 0;

            try
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand(objQuery.CheckLogin, con);

                cmd.Parameters.AddWithValue("@UserName", objLoginDetails.UserName);
                cmd.Parameters.AddWithValue("@Password", objLoginDetails.Password);
                val = cmd.ExecuteNonQuery();

                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                DataTable        dt = new DataTable();
                da.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    val = 1;
                }
                else
                {
                    val = 0;
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            finally
            {
                con.Close();
            }
            return(val);
        }
Пример #25
0
        public static pessoa verificarLogin(string cpf, string senha)
        {
            using (LoginEntities entities = new LoginEntities())
            {
                try
                {
                    pessoa pessoaLogada = new pessoa();
                    pessoaLogada = entities.pessoas.SqlQuery("select * from pessoa where cpf='" + cpf + "' and senha='" + senha + "'").Single();

                    if (pessoaLogada == null || pessoaLogada.cpf.Equals(null) || pessoaLogada.cpf.Equals(""))
                    {
                        return(null);
                    }
                    else
                    {
                        return(pessoaLogada);
                    }
                }
                catch (Exception e)
                {
                    return(null);
                }
            }
        }
Пример #26
0
 public IActionResult Insert([FromBody] LoginEntities loginEntities)
 {
     queryCommand.Insert(loginEntities);
     return(Ok(HttpStatusCode.OK));
 }
        public HttpResponseMessage LoginEmployee(LoginEntities model)
        {
            var HttpResponse = new HttpResponseMessage();

            try
            {
                // IF MODEL IS NULL
                if (model == null)
                {
                    HttpResponse     = new HttpResponseMessage(HttpStatusCode.NoContent);
                    response.Code    = HttpStatusCode.NoContent;
                    response.Message = "No Content";
                    response.Result  = null;

                    HttpResponse.Content = new StringContent(JsonConvert.SerializeObject(response));
                    HttpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    return(HttpResponse);
                }
                Employee employee = new Employee();

                //VALIDATE DATA
                if (!String.IsNullOrEmpty(model.users) || !String.IsNullOrEmpty(model.password))
                {
                    employee = context.Employee.FirstOrDefault(x => x.Users == model.users && x.State == ConstantHelper.Status.ACTIVE);

                    //EMPLOYEE DO NOT EXIST
                    if (employee == null)
                    {
                        HttpResponse     = new HttpResponseMessage(HttpStatusCode.NotFound);
                        response.Code    = HttpStatusCode.NotFound;
                        response.Message = "Not Found";
                        response.Result  = null;

                        HttpResponse.Content = new StringContent(JsonConvert.SerializeObject(response));
                        HttpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        return(HttpResponse);
                    }

                    var password = CipherLogic.Cipher(CipherAction.Decrypt, CipherType.UserPassword, employee.Password);

                    //COMPARATION PASSWORD
                    if (password == model.password)
                    {
                        //DOMAIN
                        String baseAddress = "http://chemita96-001-site1.dtempurl.com";
                        //String baseAddress = "http://localhost:16669";
                        //CREATE A NEW TOKEN FOR EMPLOYEE
                        if (!employee.TokenEmployeeId.HasValue)
                        {
                            var           fecha         = DateTime.Now.AddHours(-7);
                            TokenEntities tokenEntities = new TokenEntities();
                            using (var client = new HttpClient())
                            {
                                var form = new Dictionary <string, string>
                                {
                                    { "grant_type", "password" },
                                    { "username", employee.Users },
                                    { "password", password },
                                };
                                var tokenResponse = client.PostAsync(baseAddress + "/oauth/token", new FormUrlEncodedContent(form)).Result;
                                //CONVERT
                                tokenEntities = tokenResponse.Content.ReadAsAsync <TokenEntities>(new[] { new JsonMediaTypeFormatter() }).Result;
                                if (tokenEntities.accessToken == null)
                                {
                                    HttpResponse     = new HttpResponseMessage(HttpStatusCode.BadGateway);
                                    response.Code    = HttpStatusCode.BadRequest;
                                    response.Message = "Bad Request";
                                    response.Result  = null;

                                    HttpResponse.Content = new StringContent(JsonConvert.SerializeObject(response));
                                    HttpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                                    return(HttpResponse);
                                }
                                else
                                {
                                    //IF TOKEN IS NULL ADD KEY AND SAVE IN DATA BASE
                                    var tokenEmployee = new TokenEmployee();
                                    context.TokenEmployee.Add(tokenEmployee);
                                    tokenEmployee.AccessToken   = tokenEntities.accessToken;
                                    tokenEmployee.ExpireInToken = tokenEntities.expiresIn;
                                    tokenEmployee.ErrorToken    = tokenEntities.error;
                                    tokenEmployee.TypeToken     = tokenEntities.tokenType;
                                    tokenEmployee.RefreshToken  = tokenEntities.refreshToken;
                                    tokenEmployee.Issued        = fecha;
                                    tokenEmployee.Expires       = fecha.AddHours(24);
                                    tokenEmployee.State         = ConstantHelper.Status.ACTIVE;
                                    context.SaveChanges();
                                    //LINK EMPLOYEE WITH TOKEN
                                    employee.TokenEmployeeId = tokenEmployee.TokenEmployeeId;
                                    context.SaveChanges();
                                }
                            }

                            //SHOW HOW TO JSON
                            token.accessToken  = tokenEntities.accessToken;
                            token.tokenType    = tokenEntities.tokenType;
                            token.expiresIn    = tokenEntities.expiresIn;
                            token.refreshToken = tokenEntities.refreshToken;
                            token.username     = employee.Users;
                            token.issued       = fecha;
                            token.expires      = fecha.AddHours(24);
                            var company = context.Company.FirstOrDefault(x => x.EmployeeId == employee.EmployeeId);
                            token.companyId  = company.CompanyId;
                            token.employeeId = employee.EmployeeId;

                            response.Code    = HttpStatusCode.OK;
                            response.Message = "Success";
                            response.Result  = token;

                            //RESULT
                            HttpResponse         = new HttpResponseMessage(HttpStatusCode.OK);
                            HttpResponse.Content = new StringContent(JsonConvert.SerializeObject(response));
                            HttpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        }
                        else if (employee.TokenEmployeeId.HasValue)
                        {
                            //verificar si el token esta activo
                            bool verificar = ValidateToken(employee.TokenEmployee.AccessToken);
                            if (!verificar)
                            {
                                var tokenString   = employee.TokenEmployee.AccessToken;
                                var employeeData  = context.Employee.FirstOrDefault(x => x.TokenEmployee.AccessToken == tokenString);
                                var pwd           = CipherLogic.Cipher(CipherAction.Decrypt, CipherType.UserPassword, employee.Password);
                                var newToken      = GeneretaToken(employeeData.Users, pwd);
                                var tokenEmployee = context.TokenEmployee.FirstOrDefault(x => x.AccessToken == newToken);

                                token.accessToken  = tokenEmployee.AccessToken;
                                token.tokenType    = tokenEmployee.TypeToken;
                                token.expiresIn    = tokenEmployee.ExpireInToken;
                                token.refreshToken = tokenEmployee.RefreshToken;
                                token.username     = employeeData.Users;
                                token.issued       = tokenEmployee.Issued;
                                token.expires      = tokenEmployee.Expires;
                                var company = context.Company.FirstOrDefault(x => x.EmployeeId == employee.EmployeeId);
                                token.companyId  = company.CompanyId;
                                token.employeeId = employee.EmployeeId;
                            }
                            {
                                token.accessToken  = employee.TokenEmployee.AccessToken;
                                token.tokenType    = employee.TokenEmployee.TypeToken;
                                token.expiresIn    = employee.TokenEmployee.ExpireInToken;
                                token.refreshToken = employee.TokenEmployee.RefreshToken;
                                token.username     = employee.Users;
                                token.issued       = employee.TokenEmployee.Issued;
                                token.expires      = employee.TokenEmployee.Expires;
                                var company = context.Company.FirstOrDefault(x => x.EmployeeId == employee.EmployeeId);
                                token.companyId  = company.CompanyId;
                                token.employeeId = employee.EmployeeId;
                            }
                            response.Code    = HttpStatusCode.OK;
                            response.Message = "Success";
                            response.Result  = token;

                            HttpResponse         = new HttpResponseMessage(HttpStatusCode.OK);
                            HttpResponse.Content = new StringContent(JsonConvert.SerializeObject(response));
                            HttpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        }
                    }
                }

                //EMPLOYEE WAS DELETE
                if (employee.State == ConstantHelper.Status.INACTIVE)
                {
                    HttpResponse     = new HttpResponseMessage(HttpStatusCode.NotFound);
                    response.Code    = HttpStatusCode.NotFound;
                    response.Message = "Not Found";
                    response.Result  = null;

                    HttpResponse.Content = new StringContent(JsonConvert.SerializeObject(response));
                    HttpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    return(HttpResponse);
                }
                return(HttpResponse);
            }
            catch (Exception ex)
            {
                HttpResponse         = new HttpResponseMessage(HttpStatusCode.BadGateway);
                response.Message     = "Bad Gateway";
                response.Result      = null;
                HttpResponse.Content = new StringContent(JsonConvert.SerializeObject(response));
                HttpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return(HttpResponse);
            }
        }
        public void Login(LoginEntities model)
        {
            if (!String.IsNullOrEmpty(model.users) || !String.IsNullOrEmpty(model.password))
            {
                var employee = context.Employee.FirstOrDefault(x => x.Users == model.users && x.State == ConstantHelper.Status.ACTIVE);


                var password = CipherLogic.Cipher(CipherAction.Decrypt, CipherType.UserPassword, employee.Password);

                //COMPARATION PASSWORD
                if (password == model.password)
                {
                    //DOMAIN
                    //String baseAddress = "http://chemita96-001-site1.dtempurl.com";
                    String baseAddress = "http://localhost:16669";
                    //CREATE A NEW TOKEN FOR EMPLOYEE
                    if (!employee.TokenEmployeeId.HasValue)
                    {
                        var           fecha         = DateTime.Now.AddHours(-7);
                        TokenEntities tokenEntities = new TokenEntities();
                        using (var client = new HttpClient())
                        {
                            var form = new Dictionary <string, string>
                            {
                                { "grant_type", "password" },
                                { "username", employee.Users },
                                { "password", password },
                            };
                            var tokenResponse = client.PostAsync(baseAddress + "/oauth/token", new FormUrlEncodedContent(form)).Result;
                            //CONVERT
                            tokenEntities = tokenResponse.Content.ReadAsAsync <TokenEntities>(new[] { new JsonMediaTypeFormatter() }).Result;
                            if (tokenEntities.accessToken != null)
                            {
                                //IF TOKEN IS NULL ADD KEY AND SAVE IN DATA BASE
                                var tokenEmployee = new TokenEmployee();
                                context.TokenEmployee.Add(tokenEmployee);
                                tokenEmployee.AccessToken   = tokenEntities.accessToken;
                                tokenEmployee.ExpireInToken = tokenEntities.expiresIn;
                                tokenEmployee.ErrorToken    = tokenEntities.error;
                                tokenEmployee.TypeToken     = tokenEntities.tokenType;
                                tokenEmployee.RefreshToken  = tokenEntities.refreshToken;
                                tokenEmployee.Issued        = fecha;
                                tokenEmployee.Expires       = fecha.AddHours(24);
                                tokenEmployee.State         = ConstantHelper.Status.ACTIVE;
                                context.SaveChanges();
                                //LINK EMPLOYEE WITH TOKEN
                                employee.TokenEmployeeId = tokenEmployee.TokenEmployeeId;
                                context.SaveChanges();
                            }
                        }

                        //SHOW HOW TO JSON
                        token.accessToken  = tokenEntities.accessToken;
                        token.tokenType    = tokenEntities.tokenType;
                        token.expiresIn    = tokenEntities.expiresIn;
                        token.refreshToken = tokenEntities.refreshToken;
                        token.username     = employee.Users;
                        token.issued       = fecha;
                        token.expires      = fecha.AddHours(24);
                    }
                }
            }
        }
Пример #29
0
        public static string alterarPessoa(pessoa p)
        {
            using (LoginEntities entities = new LoginEntities())
            {
                try
                {
                    pessoa updatePessoa = new pessoa();
                    updatePessoa = entities.pessoas.FirstOrDefault(up => up.cpf == p.cpf);

                    if (p.nome.Equals(null) || p.nome.Equals(""))
                    {
                        updatePessoa.nome = updatePessoa.nome;
                    }
                    else
                    {
                        updatePessoa.nome = p.nome;
                    }

                    if (p.sobrenome.Equals(null) || p.sobrenome.Equals(""))
                    {
                        updatePessoa.sobrenome = updatePessoa.sobrenome;
                    }
                    else
                    {
                        updatePessoa.sobrenome = p.sobrenome;
                    }

                    if (p.email.Equals(null) || p.email.Equals(""))
                    {
                        updatePessoa.email = updatePessoa.email;
                    }
                    else
                    {
                        updatePessoa.email = p.email;
                    }

                    if (p.idade.Equals(null) || p.idade.Equals(""))
                    {
                        updatePessoa.idade = updatePessoa.idade;
                    }
                    else
                    {
                        updatePessoa.idade = p.idade;
                    }

                    if (p.sexo.Equals(null) || p.sexo.Equals(""))
                    {
                        updatePessoa.sexo = updatePessoa.sexo;
                    }
                    else
                    {
                        updatePessoa.sexo = p.sexo;
                    }

                    if (p.senha.Equals(null) || p.senha.Equals(""))
                    {
                        updatePessoa.senha = updatePessoa.senha;
                    }
                    else
                    {
                        updatePessoa.senha = p.senha;
                    }

                    entities.SaveChanges();
                    return("Dados do Cadastro foram atualizados com sucesso!");
                }
                catch (Exception e)
                {
                    return("Erro: " + e.Message);
                }
            }
        }
Пример #30
0
        public static string cadastrarPessoa(pessoa p)
        {
            using (LoginEntities entities = new LoginEntities())
            {
                try
                {
                    pessoa createPessoa = new pessoa();

                    bool cpfaux       = false;
                    bool nomeaux      = false;
                    bool sobrenomeaux = false;
                    bool emailaux     = false;
                    bool idadeaux     = false;
                    bool sexoaux      = false;
                    bool senhaaux     = false;

                    if (p.cpf.Equals(null) || p.cpf.Equals("") || p.cpf.Length < 11)
                    {
                        cpfaux = false;
                    }
                    else
                    {
                        createPessoa.cpf = p.cpf;
                        cpfaux           = true;
                    }

                    if (p.nome.Equals(null) || p.nome.Equals(""))
                    {
                        nomeaux = false;
                    }
                    else
                    {
                        createPessoa.nome = p.nome;
                        nomeaux           = true;
                    }

                    if (p.sobrenome.Equals(null) || p.sobrenome.Equals(""))
                    {
                        sobrenomeaux = false;
                    }
                    else
                    {
                        createPessoa.sobrenome = p.sobrenome;
                        sobrenomeaux           = true;
                    }

                    if (p.email.Equals(null) || p.email.Equals(""))
                    {
                        emailaux = true;
                    }
                    else
                    {
                        createPessoa.email = p.email;
                        emailaux           = true;
                    }

                    if (p.idade.Equals(null) || p.idade.Equals(""))
                    {
                        idadeaux = false;
                    }
                    else
                    {
                        createPessoa.idade = p.idade;
                        idadeaux           = true;
                    }

                    if (p.sexo.Equals(null) || p.sexo.Equals(""))
                    {
                        sexoaux = false;
                    }
                    else
                    {
                        createPessoa.sexo = p.sexo;
                        sexoaux           = true;
                    }

                    if (p.senha.Equals(null) || p.senha.Equals(""))
                    {
                        senhaaux = false;
                    }
                    else
                    {
                        createPessoa.senha = p.senha;
                        senhaaux           = true;
                    }


                    if (cpfaux == true && nomeaux == true && sobrenomeaux == true && emailaux == true && idadeaux == true && sexoaux == true && senhaaux == true)
                    {
                        entities.pessoas.Add(createPessoa);
                        entities.SaveChanges();
                        return("Cadastro realizado com sucesso!");
                    }
                    else
                    {
                        return(null);
                    }
                }
                catch (Exception e)
                {
                    return("Erro: " + e.Message);
                }
            }
        }