示例#1
0
        private async Task <RestaurantOwner> LoginUser(LoginCustomer loginCustomer)
        {
            RestaurantOwner restaurantOwner = _context.RestaurantOwners.Include(r => r.Restaurant).FirstOrDefault(r => r.email == loginCustomer.Username);

            if (restaurantOwner.password == loginCustomer.Password)
            {
                return(restaurantOwner);
            }
            return(null);
            //   var client = _httpClientFactory.CreateClient();
            //   client.BaseAddress = new Uri("http://127.0.0.1:8000");
            //   client.DefaultRequestHeaders.Accept.Clear();
            //   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //   var formContent = new FormUrlEncodedContent(new[]
            //{

            //    new KeyValuePair<string, string>("email", loginCustomer.Username),
            //    new KeyValuePair<string, string>("password", loginCustomer.Password),
            //});

            //   using var httpResponse =
            //       await client.PostAsync("/rest-auth/login/", formContent);

            //   if (httpResponse.IsSuccessStatusCode)
            //   {

            //       return true;
            //   }
            //   else
            //   {
            //       return false;
            //   }
        }
示例#2
0
        public List <Customer> getCustomersByMatchIdAndPassword(LoginCustomer customer)
        {
            List <Customer> customersList = (from cust in dal.customers
                                             where cust.customerId.Equals(customer.customerId) &&
                                             cust.customerPassword.Equals(customer.customerPassword)
                                             select cust).ToList <Customer>();

            return(customersList);
        }
示例#3
0
        public async Task <IActionResult> LCustomer([FromBody] Login customer)
        {
            LoginCustomer login = new LoginCustomer
            {
                CustomerLogin = customer
            };

            return(login.Excute());
        }
示例#4
0
        private bool isLoginCustomerValid(LoginCustomer loginCustomer)
        {
            bool isValid = false;

            if (isPasswordValid(loginCustomer.Password) &&
                isUsernameValid(loginCustomer.Username))
            {
                isValid = true;
            }

            return(isValid);
        }
示例#5
0
        public ActionResult Login(LoginCustomer login, string ReturnUrl = "")
        {
            string message = "";

            using (PharmacySystemEntities dc = new PharmacySystemEntities())
            {
                var v = dc.CustomerLogins.Where(a => a.Email == login.Email).FirstOrDefault();
                if (v != null)
                {
                    if (v.IsEmailVerified == false)
                    {
                        ViewBag.n       = 1;
                        message         = "Incorrect EmailID or Password";
                        ViewBag.Message = message;
                        return(View("Login"));
                    }
                    if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0)
                    {
                        int    timeout   = login.RememberMe ? 525600 : 20; // 525600 min = 1 year
                        var    ticket    = new FormsAuthenticationTicket(login.Email, login.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);


                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            Session["Customer"] = v.Email;
                            return(RedirectToAction("Index", "CustomerHome"));
                        }
                    }
                    else
                    {
                        ViewBag.n = 1;
                        message   = "Incorrect EmailID or Password";
                    }
                }
                else
                {
                    ViewBag.n = 1;
                    message   = "Incorrect EmailID or Password";
                }
            }
            ViewBag.Message = message;
            return(View());
        }
示例#6
0
        private bool isLoginModelEmpty(LoginCustomer loginCustomer)
        {
            bool isEmpty = true;

            if (loginCustomer != null &&
                !string.IsNullOrEmpty(loginCustomer.Username) &&
                !string.IsNullOrEmpty(loginCustomer.Password)
                )
            {
                isEmpty = false;
            }
            return(isEmpty);
        }
示例#7
0
        public CustomerUser LoginCustome(LoginCustomer loginCustomerAccount)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    using (connection)
                    {
                        connection.Open();
                        SqlCommand cmd = new SqlCommand("FetchCustomerRecord", connection)
                        {
                            CommandType = CommandType.StoredProcedure
                        };
                        cmd.Parameters.AddWithValue("Email", loginCustomerAccount.Email);
                        cmd.Parameters.AddWithValue("Password", loginCustomerAccount.Password);
                        var returnParameter = cmd.Parameters.Add("@Result", SqlDbType.Int);
                        returnParameter.Direction = ParameterDirection.ReturnValue;

                        CustomerUser  customer = new CustomerUser();
                        SqlDataReader rd       = cmd.ExecuteReader();
                        var           result   = returnParameter.Value;

                        if (result != null && result.Equals(2))
                        {
                            throw new Exception("Email not registered");
                        }
                        if (result != null && result.Equals(3))
                        {
                            throw new Exception("wrong password");
                        }
                        if (rd.Read())
                        {
                            customer.CustomerID = rd["CustomerID"] == DBNull.Value ? default : rd.GetInt64("CustomerID");

                                                  customer.CustomerFirstName = rd["CustomerFirstName"] == DBNull.Value ? default : rd.GetString("CustomerFirstName");

                                                                               customer.CustomerLastName = rd["CustomerLastName"] == DBNull.Value ? default : rd.GetString("CustomerLastName");

                                                                                                           customer.Email = rd["Email"] == DBNull.Value ? default : rd.GetString("Email");

                                                                                                                            customer.PhoneNumber = rd["PhoneNumber"] == DBNull.Value ? default : rd.GetInt64("PhoneNumber");
                        }
                        return(customer);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#8
0
        public async Task <IActionResult> Login(LoginCustomer loginCustomer)
        {
            RestaurantOwner restaurantOwner = await LoginUser(loginCustomer);

            if (restaurantOwner != null)
            {
                // MyapiCustomer customer = _context.MyapiCustomers.FirstOrDefault(c => c.Email == loginCustomer.Username);
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, restaurantOwner.Restaurant.Name),
                    new Claim(ClaimTypes.NameIdentifier, restaurantOwner.Restaurant.Id.ToString()),
                    new Claim("FullName", restaurantOwner.email)
                };

                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var authProperties = new AuthenticationProperties
                {
                    AllowRefresh = true,
                    // Refreshing the authentication session should be allowed.

                    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
                    // The time at which the authentication ticket expires. A
                    // value set here overrides the ExpireTimeSpan option of
                    // CookieAuthenticationOptions set with AddCookie.

                    IsPersistent = true,
                    // Whether the authentication session is persisted across
                    // multiple requests. When used with cookies, controls
                    // whether the cookie's lifetime is absolute (matching the
                    // lifetime of the authentication ticket) or session-based.

                    //IssuedUtc = <DateTimeOffset>,
                    // The time at which the authentication ticket was issued.

                    //RedirectUri = <string>
                    // The full path or absolute URI to be used as an http
                    // redirect response value.
                };

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);

                return(RedirectToAction("Index", "Orders"));
            }
            return(View());
        }
示例#9
0
        public ActionResult Authenticate(LoginCustomer loginCustomer)
        {
            CustomerDB      customerModelDB = new CustomerDB();
            List <Customer> customers       = customerModelDB.getCustomersByMatchIdAndPassword(loginCustomer);

            if (customers.Count > 0)
            {
                FormsAuthentication.SetAuthCookie("cookie", false);
                CurrentCustomer.customerId = loginCustomer.customerId;

                return(RedirectToAction("Index", "Customer", customers[0]));
            }

            //msg: user not exists
            return(View("Login", new LoginCustomer()));
        }
示例#10
0
        public async Task <ActionResult> Login(LoginCustomer c, string next)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var user = await db.Customers.SingleOrDefaultAsync(x => x.Email == c.Email);

                    if (user != null)
                    {
                        var checkpwd = BCrypt.Net.BCrypt.Verify(c.Password, user.Password);
                        if (checkpwd)
                        {
                            HttpCookie cookie = new HttpCookie("InfoCustomer");
                            cookie["id"]         = user.CustomerId.ToString();
                            cookie["Email"]      = user.Email;
                            cookie["Avatar"]     = user.Avatar;
                            cookie["CreateDate"] = user.CreateDate.ToString("dd/MM/yyyy HH:mm");
                            cookie.Expires       = DateTime.Now.AddDays(2);
                            Response.Cookies.Add(cookie);
                            if (c.RememberMe == true)
                            {
                                Response.Cookies["Email"].Value   = c.Email;
                                Response.Cookies["Email"].Expires = DateTime.Now.AddDays(15);
                                ViewBag.Email = Request.Cookies["Email"].Value;
                            }
                            setAlert("", "Đăng nhập thành công !", "top-right", "success", 5000);
                            return(RedireactToLocal(next));
                        }
                        else
                        {
                            ModelState.AddModelError("Email", "Email hoặc mật khẩu không chính xác");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("Email", "Email hoặc mật khẩu không chính xác");
                    }
                }
                catch (Exception)
                {
                    setAlert("Lỗi!", "Không thể đăng nhập vào lúc này, vui lòng thử lại sau.", "bottom-left", "error", 5000);
                    return(View(c));
                }
            }
            return(View(c));
        }
示例#11
0
 //To check whether the user exists, and if so, if the credentials are correct
 public static bool User_in_DB(LoginCustomer User)
 {
     using (var db = new DatabaseContext())
     {
         DBCustomer foundUser = db.DBCustomer.FirstOrDefault(b => b.Username == User.Username);
         if (foundUser != null)
         {
             byte[] testPassword = CreateHash(User.Password, foundUser.Salt);
             bool   correctUser  = foundUser.Password.SequenceEqual(testPassword);
             return(correctUser);
         }
         else
         {
             return(false);
         }
     }
 }
示例#12
0
        public LoginReturnModel Login(LoginCustomer loginCustomer)
        {
            if (isLoginModelEmpty(loginCustomer))
            {
                throw new ArgumentException("Arguments are not valid.");
            }

            if (!isLoginCustomerValid(loginCustomer))
            {
                string passwordError = errorPasswordMessage(loginCustomer.Password);
                string usernameError = errorUsernameMessage(loginCustomer.Username);
                //throw new ArgumentException() { Data = { { "Password", passwordError }, { "Username", usernameError } } };
                throw new ArgumentException
                      {
                          Data = {     {
                                           "errors",
                                           new LoginCustomer()
                                           {
                                               Password = passwordError,
                                               Username = usernameError
                                           }
                                       } }
                      };
            }

            loginCustomer.Password = passwordToHashPass(loginCustomer.Password);

            Task <Customer> customerTask = _customersDal.FindCustomerAsync(loginCustomer);
            Customer        customer     = customerTask.Result;

            if (isEmptyCustomer(customer))
            {
                return(null);
            }
            else
            {
                string           token = generateToken(customer);
                LoginReturnModel customerWithGeneratedToken = new LoginReturnModel
                {
                    Customer = customer,
                    Token    = token
                };
                return(customerWithGeneratedToken);
            }
        }
示例#13
0
        public CustomerUser LoginCustomer(LoginCustomer loginCustomerAccount)
        {
            try
            {
                loginCustomerAccount.Password = Password.ConvertToEncrypt(loginCustomerAccount.Password);

                var result = userRL.LoginCustome(loginCustomerAccount);
                if (result != null)
                {
                    result.token = userRL.CreateToken(result);
                }
                return(result);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public IActionResult Login([FromBody] LoginCustomer loginCustomer)
        {
            try
            {
                LoginReturnModel customer = _customersLogic.Login(loginCustomer);

                if (customer == null)
                {
                    return(Unauthorized(new { message = _customersLogic.loginErrorMessage(customer) }));
                }

                return(Ok(customer));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Data));
            }
        }
示例#15
0
 public ActionResult Login(LoginCustomer customer)
 {
     try
     {
         if (ModelState.IsValid)
         {
             var getUser = (from s in db.Customers where s.Email_id == customer.Email_id select s).Single();
             if (getUser != null)
             {
                 string password = (getUser.Password);
                 if (String.IsNullOrEmpty(password))
                 {
                     ViewBag.ErrorMessage = "Please entrer the Password!!";
                     return(View());
                 }
                 var query = (from s in db.Customers where (s.Email_id == customer.Email_id) && customer.Password.Equals(password) select s).Single();
                 if (query != null)
                 {
                     Session["Username"] = getUser.Customer_name;
                     Session["UserId"]   = getUser.Customer_id;
                     //return RedirectToAction("Edit", "Customer");
                     return(RedirectToAction("HomePage", "Home"));
                 }
                 ViewBag.ErrorMessage = "Invalid Password";
                 return(View());
             }
             ViewBag.ErrorMessagae = "Invalid Username/EmailId or Password";
             return(View());
         }
         // ViewBag.ErrorMessage = "Invalid UserName or Password";
         return(View());
     }
     catch (Exception)
     {
         //throw e;
         ViewBag.ErrorMessage = "Invalid Details!! please enter correct details";
         return(View());
     }
 }
示例#16
0
 public IActionResult LoginUser(LoginCustomer Customer)
 {
     if (Customer == null)
     {
         return(BadRequest("Customer is null."));
     }
     try
     {
         CustomerUser result = bookBL.LoginCustomer(Customer);
         if (result != null)
         {
             return(Ok(new { success = true, Message = "Customer login Successful", Customer = result }));
         }
         else
         {
             return(BadRequest(new { success = false, Message = "Customer login Unsuccessful" }));
         }
     }
     catch (Exception exception)
     {
         return(BadRequest(new { success = false, exception.Message }));
     }
 }
示例#17
0
 public ActionResult Login(LoginCustomer LoggedIn)
 {
     if (ModelState.IsValid)
     {
         if (SecurityImplementation.User_in_DB(LoggedIn))
         {
             // Username && Password correct
             Session["LoggedIn"] = "true";
             //Sesion to store username
             Session["Username"] = LoggedIn.Username;
             //  ViewBag.InLogged = true;
             return(RedirectToAction("Index", "Home"));
         }
         else
         {
             // Username && Password wrong
             Session["LoggedIn"] = "false";
             // ViewBag.InLogged = false;
             return(View("LoginFailed"));
         }
     }
     // Check to see if Login Credentials are OK
     return(View());
 }
示例#18
0
 public async Task <Customer> FindCustomerAsync(LoginCustomer loginCustomer)
 {
     return(await _context.Customers.FirstOrDefaultAsync(e => e.Username == loginCustomer.Username && e.Password == loginCustomer.Password));
 }