Example #1
0
        // GET: Grade
        public ActionResult Index(int id)
        {
            if (this.Session["UserProfile"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            UserProfileSessionData upsd = Session["UserProfile"] as UserProfileSessionData;
            IList <Object[]>       lista;

            WirtualnyDziennik.Models.Przedmioty.ListaDostepnych = new List <SelectListItem>();

            IQuery s = null;

            using (ISession session = NhibernateSession.OpenSession())
            {
                //Odbiorca = session.Query<Uzytkownicy>().Where(b => b.id == id).FirstOrDefault();
                if (upsd.Typ == "UCZEN")
                {
                    s = session.CreateSQLQuery("select dziennikucznia.ocena,typoceny.nazwa,przedmioty.nazwa as PRZEDMIOT, TO_CHAR(dziennikucznia.data,'DD/MM/YYYY') as DATA from typoceny, uzytkownicy, klasauczen, dziennikucznia, planlekcji, przedmioty where dziennikucznia.ocena!=0 and uzytkownicy.id =" + id + " and uzytkownicy.id = klasauczen.uzytkownik_id and klasauczen.klasauczen_id = dziennikucznia.klasauczen_id and typoceny.id=dziennikucznia.typoceny_id and dziennikucznia.planlekcji_id = planlekcji.planlekcji_id and planlekcji.przedmiot_id = przedmioty.id");
                }
                if (upsd.Typ == "RODZIC")
                {
                    s = session.CreateSQLQuery("select uzytkownicy.imie as Imie ,uzytkownicy.nazwisko as Nazwisko ,dziennikucznia.ocena,typoceny.nazwa,przedmioty.nazwa as PRZEDMIOT, TO_CHAR(dziennikucznia.data,'DD/MM/YYYY') as DATA from typoceny,uzytkownicy, klasauczen, dziennikucznia, planlekcji, przedmioty where dziennikucznia.ocena!=0 and uzytkownicy.id in (SELECT u.id FROM uzytkownicy u WHERE EXISTS(SELECT NULL FROM rodzicuczen ru WHERE u.id = ru.uczen_id AND ru.rodzic_id =" + id + ")) and uzytkownicy.id = klasauczen.uzytkownik_id and typoceny.id=dziennikucznia.typoceny_id and klasauczen.klasauczen_id = dziennikucznia.klasauczen_id and dziennikucznia.planlekcji_id = planlekcji.planlekcji_id and planlekcji.przedmiot_id = przedmioty.id");
                }

                lista = s.List <Object[]>();
            }
            return(View(lista));
        }
Example #2
0
        /// <summary>
        /// Авторизация пользователя, и сохранение данных о нем в куки
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private bool authenticate(UserViewModel user)
        {
            var userProfile = new UserProfileSessionData(userRepository.GetUser(user.email, user.pwd));

            UserStorage.Set(userProfile);

            userSessionRepository.CreateUserSession(new Domain.Core.UserSession
            {
                SessionID = Session.SessionID,
                UserID    = userProfile.ID,
                Start     = DateTime.Now,
                IP        = Request.UserHostAddress
            });
            try
            {
                userSessionRepository.Save();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Ошибка при создании UserSession");
                return(false);
            }
            return(true);
            // return new Authenticate { IsAuthenticated = true, UserName = userProfile.Name ?? userProfile.Login };
        }
Example #3
0
 public ActionResult Login(string haslo, string login)
 {
     try
     {
         using (ISession session = NhibernateSession.OpenSession())
         {
             Uzytkownicy U = session.Query <Uzytkownicy>().Where(b => b.nazwa == login).FirstOrDefault();
             if (U.haslo == haslo)
             {
                 UserProfileSessionData UserLogged = new UserProfileSessionData
                 {
                     Name         = U.nazwa,
                     UserId       = U.id,
                     EmailAddress = U.email,
                     Typ          = U.typu.nazwa
                 };
                 this.Session.Add("UserProfile", UserLogged);
                 // this.Session["User"] = UserLogged;
             }
             else
             {
                 return(RedirectToAction("Index"));
             }
         }
     }
     catch (Exception e)
     {
         return(RedirectToAction("Index"));
     }
     return(RedirectToAction("Index"));
 }
Example #4
0
        // GET: Grade
        public ActionResult Index(int id)
        {
            if (this.Session["UserProfile"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            UserProfileSessionData upsd = Session["UserProfile"] as UserProfileSessionData;
            IList <Object[]>       lista;
            IQuery s = null;

            using (ISession session = NhibernateSession.OpenSession())
            {
                //Odbiorca = session.Query<Uzytkownicy>().Where(b => b.id == id).FirstOrDefault();
                if (upsd.Typ == "UCZEN")
                {
                    s = session.CreateSQLQuery("select dziennikucznia.obecnosc,przedmioty.nazwa as PRZEDMIOT, TO_CHAR(dziennikucznia.data,'DD/MM/YYYY') as DATA from uzytkownicy, klasauczen, dziennikucznia, planlekcji, przedmioty where uzytkownicy.id =" + id + " and uzytkownicy.id = klasauczen.uzytkownik_id and klasauczen.klasauczen_id = dziennikucznia.klasauczen_id and dziennikucznia.planlekcji_id = planlekcji.planlekcji_id and planlekcji.przedmiot_id = przedmioty.id");
                }
                if (upsd.Typ == "RODZIC")
                {
                    s = session.CreateSQLQuery("select uzytkownicy.imie as Imie ,uzytkownicy.nazwisko as Nazwisko ,dziennikucznia.obecnosc,przedmioty.nazwa as PRZEDMIOT, TO_CHAR(dziennikucznia.data,'DD/MM/YYYY') as DATA from uzytkownicy, klasauczen, dziennikucznia, planlekcji, przedmioty where uzytkownicy.id in (SELECT u.id FROM uzytkownicy u WHERE EXISTS(SELECT NULL FROM rodzicuczen ru WHERE u.id = ru.uczen_id AND ru.rodzic_id = " + id + ")) and uzytkownicy.id = klasauczen.uzytkownik_id and klasauczen.klasauczen_id = dziennikucznia.klasauczen_id and dziennikucznia.planlekcji_id = planlekcji.planlekcji_id and planlekcji.przedmiot_id = przedmioty.id");
                }

                /*lista =session.CreateSQLQuery("select uzytkownicy.nazwa as UCZEN ,dziennikucznia.ocena,przedmioty.nazwa as PRZEDMIOT,dziennikucznia.data as DATA from KlasaUczen, Klasy, planlekcji, przedmioty, dziennikucznia, uzytkownicy where uzytkownicy.id = klasauczen.uzytkownik_id and klasauczen.klasa_id = klasy.id and klasy.id = planlekcji.klasa_id  and planlekcji.planlekcji_id = dziennikucznia.planlekcji_id and dziennikucznia.klasauczen_id = klasauczen.klasauczen_id")
                 *   .AddScalar("UCZEN",NHibernateUtil.String)
                 *   .AddScalar("OCENA",NHibernateUtil.Double)
                 *   .AddScalar("PRZEDMIOT",NHibernateUtil.String)
                 *   .AddScalar("DATA",NHibernateUtil.DateTime).List<Object[]>();*/
                lista = s.List <Object[]>();
            }
            return(View(lista));
        }
 public ActionResult Login(LoginRegisterViewModel model)
 {
     if (ModelState.IsValid)
     {
         var user = Db.ApplicationUsers.FirstOrDefault(x => (x.Email == model.Email && x.Password == model.Password));
         if (user != null)
         {
             var userRole    = Db.UserRoles.FirstOrDefault(x => x.ID == user.RoleID).Label;
             var profileData = new UserProfileSessionData
             {
                 FullName = user.Firstname + " " + user.Lastname,
                 UserId   = user.ID,
                 UserRole = userRole
             };
             this.Session["UserProfile"] = profileData;
             return(RedirectToAction("Index", "Home"));
         }
         var error = new ErrorViewModel
         {
             ErrorTitle   = "Login Failed",
             ErrorMessage = "You entered wrong password or email"
         };
         return(View("~/Views/Error/ErrorPage.cshtml", error));
     }
     return(View("~/Views/Account/Index.cshtml"));
 }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="user">Модель plan2plan.Domain.Core.User </param>
        public static UserProfileSessionData Set(User user)
        {
            var userProfile = new UserProfileSessionData(user);

            UserStorage.Set(userProfile);
            return(userProfile);
        }
 public JsonResult UpdateUserInfor(UserProfileViewModel model)
 {
     try
     {
         var user = Db.ApplicationUsers.Find(model.ID);
         user.Firstname = model.Firstname;
         user.Lastname  = model.Lastname;
         user.Phone     = model.Phone;
         user.Country   = model.Country;
         if (Db.SaveChanges() > 0)
         {
             var profileData = new UserProfileSessionData
             {
                 FullName = user.Firstname + " " + user.Lastname,
                 UserId   = user.ID,
                 UserRole = user.UserRole.Label
             };
             this.Session["UserProfile"] = profileData;
             return(Json(new { success = true, message = "Update user information successfully! " }));
         }
         return(Json(new { success = false, message = "Oops! Something went wrong" }));
     }
     catch (Exception e)
     {
         return(Json(e.Message));
     }
 }
Example #8
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            UserProfileSessionData UserProfile = (UserProfileSessionData)HttpContext.Current.Session["UserProfile"];
            string         UserName            = UserProfile.UserName;
            int            UserId     = UserProfile.UserId;
            UrlSessionData CurrentUrl = (UrlSessionData)HttpContext.Current.Session["CurrentUrl"];

            string ActionName     = HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString();
            string ControllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString() + "Controller";

            AccessRightsRepository uar   = new AccessRightsRepository();
            string ControllerDescription = EnumService.GetControllerDescription(ControllerName);
            string ActionDescription     = EnumService.GetActionDescription(ControllerName, ActionName);
            bool   uacresult             = uar.UserAccessCheck(UserId, ControllerName, ActionName);

            if (UserName.ToLower() != "admin" && !uacresult && ControllerName != ControllerDescription && ActionDescription != null)
            {
                string RedirectUrl = "/Home/AccessRightsError?CName=" + CurrentUrl.Controller + "&AName=" + CurrentUrl.Action;
                //filterContext.HttpContext.Response.Redirect(RedirectUrl,false);

                filterContext.Result = new RedirectToRouteResult("Error_Deafult", new RouteValueDictionary(new { controller = "Home", action = "AccessRightsError", CName = CurrentUrl.Controller, AName = CurrentUrl.Action }));
            }
            else
            {
                CurrentUrl.Controller = ControllerName.Substring(0, ControllerName.IndexOf("Controller"));
                CurrentUrl.Action     = ActionName;
                HttpContext.Current.Session["CurrentUrl"] = CurrentUrl;
                base.OnActionExecuting(filterContext);
            }
        }
Example #9
0
 public ActionResult Message(Tresc model)
 {
     if (this.Session["UserProfile"] == null)
     {
         return(RedirectToAction("Index", "Home"));
     }
     try
     {
         using (ISession session = NhibernateSession.OpenSession())
         {
             UserProfileSessionData uspd = this.Session["UserProfile"] as UserProfileSessionData;
             model.OD        = uspd.Name;
             model.TypTresci = (TypTresci)session.Load("TypTresci", 2);
             using (ITransaction transaction = session.BeginTransaction())
             {
                 session.Save(model);
                 transaction.Commit();
             }
         }
         return(View());
     }
     catch (Exception e)
     {
         return(View());
     }
 }
Example #10
0
        public ActionResult Login(LoginModel mod)
        {
            DBDataContext db = new DBDataContext();

            if (ModelState.IsValid)
            {
                var user = db.Customers.SingleOrDefault(t => t.Username == mod.Username && t.Password == mod.Password);
                if (user == null)
                {
                    return(Json(new { Result = false }));
                }
                else
                {
                    var profileData = new UserProfileSessionData
                    {
                        UserId       = user.ID,
                        EmailAddress = user.EmailAddress,
                        FullName     = user.FirstName + " " + user.LastName
                    };

                    this.Session["UserProfile"] = profileData;
                    return(Json(new
                    {
                        Result = true,
                        FullName = user.FirstName + " " + user.LastName
                    }));
                }
            }
            return(Json(new { Result = false }));
        }
Example #11
0
        /// <summary>
        /// Сохраняет объект пользователся в сессию
        /// </summary>
        /// <param name="userProfileSessionData">Модель plan2plan.Domain.Core.UserProfile.UserProfileSessionData</param>
        public static void Set(UserProfileSessionData userProfileSessionData)
        {
            HttpContext.Current.Session.Add(userProfile, userProfileSessionData);

            CookieStorage.Set(userCookieName, userProfileSessionData.ID.ToString(), 365);

            FormsAuthentication.SetAuthCookie(userProfileSessionData.Email.Mail, true);
        }
Example #12
0
        public ActionResult PersonData()
        {
            var user = UserStorage.Get();

            if (user != null)
            {
                var userProfile = new UserProfileSessionData(userRepository.GetUser(user.Email.Mail, user.Password));

                return(PartialView("_PersonDataPartial", userProfile));
            }
            return(RedirectToAction("Index", "Auth"));
        }
Example #13
0
        public static UserProfileSessionData Get()
        {
            //From Session
            if (HttpContext.Current.Session[userProfile] != null)
            {
                return(HttpContext.Current.Session[userProfile] as UserProfileSessionData);
            }

            var  userID = CookieStorage.Get(userCookieName);
            Guid id;

            //From Cookies
            if (string.IsNullOrEmpty(userID) == false &&
                Guid.TryParse(userID, out id) == true)
            {
                UserRepository userRepository = new UserRepository(new plat2platContext());
                var            user           = userRepository.GetUserByID(id);

                if (user != null)
                {
                    UserProfileSessionData userProfile = new UserProfileSessionData(user);
                    UserStorage.Set(userProfile);
                    Log.Information("Get user from cookie");
                    return(userProfile);
                }
            }


            //From DB
            UserSessionRepository us          = new UserSessionRepository(new plat2platContext());
            UserSession           userSession = us.GetUserSessionBySessionID(HttpContext.Current.Session.SessionID, DateTime.Now.AddDays(-5));

            if (userSession != null)
            {
                Log.Information("Get user from DB");
                return(UserStorage.Set(userSession.User));
            }
            //if (HttpContext.Current.User.Identity != null
            //    && string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name) != null)
            //{

            //}
            //if (FormsAuthentication.GetAuthCookie()
            //{

            //}

            return(null);
        }
        public virtual async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.UserName);

                if (!user.LockoutEnabled)
                {
                    return(View("Lockout"));
                }
            }

            if (ModelState.IsValid)
            {
                var profileData = new UserProfileSessionData
                {
                    //UserId = model.Email,
                    EmailAddress = model.UserName,
                    FullName     = model.UserName
                };
                this.Session["UserProfile"] = profileData;
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Example #15
0
        public ActionResult Login(UserVM uvm)
        {
            if (ModelState.IsValid)
            {
                string          IPAddress     = GetIPAddress();
                LoginRepository repository    = new LoginRepository();
                DataOperations  dataOperation = new DataOperations();
                string          result        = repository.DoLogin(uvm.UserName, EncodeAndDecode.Base64Encode(uvm.Password), IPAddress);

                if (result == "Uğurlu")
                {
                    tbl_User     userObj     = dataOperation.GetUserByUserName(uvm.UserName);
                    tbl_Employee employeeObj = dataOperation.GetEmployeeById(userObj.EmployeeID == null ? 0 : (Int64)userObj.EmployeeID);
                    UserProfile = new UserProfileSessionData()
                    {
                        UserId     = userObj.ID,
                        EmployeeID = employeeObj.ID,
                        UserName   = userObj.UserName,
                        FirstName  = employeeObj.FirstName,
                        LastName   = employeeObj.LastName,
                    };

                    this.Session["UserProfile"] = UserProfile;
                    UrlSessionData CurrentUrl = new UrlSessionData
                    {
                        Controller = "Home",
                        Action     = "Index"
                    };
                    this.Session["CurrentUrl"] = CurrentUrl;
                    return(RedirectToAction("Index", "Home"));
                }
                else if (result == "İstifadəçi adı tapılmadı")

                {
                    ViewBag.NotValidUser = result;
                }
                else
                {
                    ViewBag.Failedcount = result;
                }
                return(View("Index"));
            }
            else
            {
                return(View("Index", uvm));
            }
        }
Example #16
0
        public ActionResult ClassesStudentList(int id, int planlekcjiid)
        {
            if (this.Session["UserProfile"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            UserProfileSessionData upsd = Session["UserProfile"] as UserProfileSessionData;
            IList <Object[]>       lista;
            IQuery s = null;

            using (ISession session = NhibernateSession.OpenSession())
            {
                s = session.CreateSQLQuery("select u.id, u.imie, u.nazwisko from uzytkownicy u, klasauczen ku, klasy k where u.id = ku.uzytkownik_id and ku.klasa_id = k.id and k.id = " + id);
                //U = session.Query<Uzytkownicy>().Where(c => c.id == session.Query<KlasaUczen>().Where(b => b.Klasy.id == session.Query<Klasy>().Where(a => a.Wychowawca.id == id).First().id).First().klasauczen_id).ToList();
                lista = s.List <Object[]>();
            }
            ViewData["planlekcjiid"] = planlekcjiid;
            return(View(lista));
        }
Example #17
0
        private bool IsValid(string email, string password)
        {
            var user = _userService.Login(new LoginUserRequest {
                Email = email, Password = password
            });

            if (user != null && user.IsSuccess)
            {
                /* Try Get Current User Role
                 */
                //this._createRole(user.RoleName);
                //this._userAddToRole(user.Username, user.RoleName);
                var roleName = new List <KeyValuePair <int, string> >();
                //roleName = user.RolePrivileges.ToDictionary(x => x.Id);
                if (user.RolePrivileges != null && user.RolePrivileges.Count() > 0)
                {
                    foreach (var role in user.RolePrivileges)
                    {
                        //this._userAddToRole(user.Username, role.Name);
                        roleName.Add(new KeyValuePair <int, string>(role.Id, role.Name));
                    }
                }
                var profileData = new UserProfileSessionData {
                    UserId = user.Id, Email = user.Email, Name = user.Username, RoleId = user.RoleId, RoleName = user.RoleName, RedirectUrl = user.ChangeModel, IsSuperAdmin = user.IsSuperAdmin, RolePrivilegeName = roleName
                };
                this.Session["LoginUser"] = profileData;
                //var authTicket = new FormsAuthenticationTicket(
                //    version:1,
                //    name : user.Username,
                //    issueDate : DateTime.Now,
                //    expiration: DateTime.Now.AddMinutes(30),
                //    isPersistent : false,
                //    userData : string.Join("|",roles)
                //    );
                //string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                //HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                //System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                FormsAuthentication.SetAuthCookie(user.Username, false);
                return(user.IsSuccess);
            }
            return(false);
        }
Example #18
0
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            //Testa se a sessão está ativa
            oUserProfile = requestContext.HttpContext.Session["TopUserProfile"] as UserProfileSessionData;
            if (oUserProfile != null && oUserProfile.oAccount != null)
            {
                //Verifica se o usuário está ativo
                oUserProfile.oAccount = oCore.iRepositories.IAccountRepository.Select(oUserProfile.oAccount.id);
                if (oUserProfile.oAccount == null || !oUserProfile.oAccount.IsActive)
                {
                    oUserProfile = null;
                }
            }

            //Set current user location
            this.Location();

            //Default ViewBags
            ViewBag.UserProfile = this.oUserProfile;
            ViewBag.CurrentLocation = this.oCurrentUserLocation;
            ViewBag.CurrentUrl = HttpUtility.UrlEncode(Request.Url.AbsoluteUri);
            ViewBag.OpenGraph = new OpenGraphViewModel();
        }
Example #19
0
        public ActionResult Login(LoginViewModel model)
        {
            try
            {
                if (!(ModelState.IsValid))
                {
                    if ((model.Username == "" || model.Username == null) && (model.Password == "" || model.Password == null))
                    {
                        ModelState.AddModelError("", "Please enter Username and Password");
                    }
                    return(View(model));
                }
                else
                {
                    UserModel UserModel = new UserModel();

                    UserProfileSessionData profileData = new UserProfileSessionData();
                    logger.Info("UserID:" + model.Username);
                    using (DBONLINETESTEntities db = new DBONLINETESTEntities())
                    {
                        tblUser user = new tblUser();
                        user = (from usr in db.tblUsers where usr.UserName == model.Username.Trim() && usr.Password == model.Password.Trim() && usr.isActive == 1 select usr).FirstOrDefault();

                        if (user == null)
                        {
                            ModelState.AddModelError("", "Access Not Allowed");
                            logger.Debug("Error In Login Method User List Is Null. ");
                            return(RedirectToAction("Access Denied", "Account"));
                        }
                        else
                        {
                            profileData.User_ID   = user.UserId;
                            profileData.User_Name = user.UserName.Trim();
                            profileData.User_Role = user.roleid;
                        }
                    }

                    this.Session["UserProfile"] = profileData;
                    logger.Debug("Session Create");

                    FormsAuthentication.SetAuthCookie(model.Username, true);

                    logger.Debug("Redirect to View Based On Role");

                    if (profileData.User_Role == 1)
                    {
                        return(RedirectToAction("AdminView", "Home"));
                    }
                    else if (profileData.User_Role == 2)
                    {
                        return(RedirectToAction("CreateQuiz", "Home"));
                    }
                    else if (profileData.User_Role == 3)
                    {
                        return(RedirectToAction("ViewQuiz", "Home"));
                    }
                }
            }
            catch (Exception ex)
            {
                //new VonageSalesController().log_action("", "Exception", ex.ToString());
                logger.Debug("Action # Account/Login , Message # " + "NT Login # " + model.Username + ex.Message, ex);
                return(RedirectToAction("AccessDenied", "Account"));
            }
            return(View(model));
        }
Example #20
0
        public ActionResult Login(Login login, string ReturnUrl)
        {
            string msg = "";

            if (Request.HttpMethod == "POST")
            {
                if (ModelState.IsValid)
                {
                    string email = login.Email;
                    string pass  = login.Password;



                    var query = _context.Employees.Where(c => c.Email == email && c.Pass == pass).FirstOrDefault();


                    if (query != null)
                    {
                        //msg = "Welcome";
                        //Session["id"] = query.EmpId;
                        //Session["fname"] = query.EmpFName;
                        //Session["lname"] = query.EmpLName;


                        var profileData = new UserProfileSessionData
                        {
                            UserId       = query.EmpId,
                            EmailAddress = query.Email,
                            FullName     = query.EmpFName + " " + query.EmpLName
                        };


                        FormsAuthentication.SetAuthCookie(query.Email, false);

                        this.Session["UserProfile"] = profileData;
                        //this.Session["Users"] = "access";


                        //return Redirect("/Home/LeaveRequest");
                        return(Redirect("index"));
                    }
                    else
                    {
                        //RedirectToAction("Login", "Home", FormMethod.Get);
                        //return Redirect(Request.UrlReferrer.PathAndQuery); //redirect de la meme page si il n'y pas de resultat
                        msg = "Email and/or Password are incorrect or does not exist.";
                        return(View(login));
                    }
                }
                else
                {
                    //return Redirect(Request.UrlReferrer.PathAndQuery);
                    return(View(login));
                }
            }
            //else
            //{
            //    return View();
            //}



            return(View());
        }
Example #21
0
        private bool IsValid(string email, string password)
        {
            var hostname = string.Empty;

            if (Request.ServerVariables["REMOTE_ADDR"] != null)
            {
                hostname = DomainHelper.GetComputerName(Request.ServerVariables["REMOTE_ADDR"]);
            }
            var user = _userService.Login(new LoginUserRequest {
                Email = email, Password = password, IpAddress = Request.UserHostAddress, Browser = Request.UserAgent, HostName = hostname
            });

            if (user != null && user.IsSuccess)
            {
                /* Try Get Current User Role
                 */
                //this._createRole(user.RoleName);
                //this._userAddToRole(user.Username, user.RoleName);
                var roleName = new List <KeyValuePair <int, string> >();
                //roleName = user.RolePrivileges.ToDictionary(x => x.Id);
                if (user.RolePrivileges != null && user.RolePrivileges.Count() > 0)
                {
                    foreach (var role in user.RolePrivileges)
                    {
                        //this._userAddToRole(user.Username, role.Name);
                        roleName.Add(new KeyValuePair <int, string>(role.Id, role.Name));
                    }
                }
                var profileData = new UserProfileSessionData {
                    UserId = user.Id, Email = user.Email, Name = user.Username, RoleId = user.RoleId, RoleName = user.RoleName, RedirectUrl = user.ChangeModel, IsSuperAdmin = user.IsSuperAdmin, RolePrivilegeName = roleName, LoginId = user.UserLogin.Id
                };
                this.Session["LoginUser"] = profileData;
                JavaScriptSerializer serializer      = new JavaScriptSerializer();
                UserViewModel        serializedModel = new UserViewModel
                {
                    Id           = user.Id,
                    Username     = user.Username,
                    Email        = user.Email,
                    RoleId       = user.RoleId,
                    RoleName     = user.RoleName,
                    IsActive     = user.IsActive,
                    IsSuperAdmin = user.IsSuperAdmin,
                    LoginId      = user.UserLogin.Id
                };

                string userData = serializer.Serialize(serializedModel);
                //FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                //    version: 1,
                //    name: user.Username,
                //    issueDate: DateTime.Now,
                //    expiration: DateTime.Now.AddMinutes(30),
                //    isPersistent: false,
                //    userData: userData
                //    );

                CustomPrincipal cp = new CustomPrincipal(serializedModel.Email);
                cp.Id            = serializedModel.Id;
                cp.Username      = serializedModel.Username;
                cp.RoleName      = serializedModel.RoleName;
                cp.IsSuperAdmin  = serializedModel.IsSuperAdmin;
                cp.Email         = serializedModel.Email;
                cp.LoginId       = serializedModel.LoginId;
                HttpContext.User = cp;
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                    1,
                    serializedModel.Email,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(120),
                    false,
                    userData);
                string     encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                //FormsAuthentication.SetAuthCookie(user.Username, false);
                return(user.IsSuccess);
            }
            return(false);
        }
        public async Task <ActionResult> Login(UsuarioLogin model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (HttpClient httpClient = new HttpClient())
            {
                HttpContent content = new FormUrlEncodedContent(new[] {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("UserName", model.UserName),
                    new KeyValuePair <string, string>("Password", model.Password)
                });

                //HttpResponseMessage result = httpClient.PostAsync("http://192.168.43.112:5656/token", content).Result;
                //HttpResponseMessage result = httpClient.PostAsync("http://localhost:5757/token", content).Result;
                HttpResponseMessage result = httpClient.PostAsync("http://localhost:5757/token", content).Result;
                string resultContent       = result.Content.ReadAsStringAsync().Result;

                switch (result.StatusCode)
                {
                case System.Net.HttpStatusCode.OK:
                    var token = JsonConvert.DeserializeObject <AuthorizationToken>(resultContent);

                    //AuthenticationProperties options = new AuthenticationProperties();

                    //options.AllowRefresh = true;
                    //options.IsPersistent = true;
                    //options.ExpiresUtc = DateTime.UtcNow.AddSeconds(int.Parse(token.expires_in));

                    var claims = new[] {
                        new Claim(ClaimTypes.Name, model.UserName),
                        new Claim("AccessToken", string.Format("Bearer {0}", token.access_token))
                    };
                    var identity = new ClaimsIdentity(claims, "ApplicationCookie");
                    Request.GetOwinContext().Authentication.SignIn(identity);
                    //Request.GetOwinContext().Authentication.SignIn(options, identity);


                    //informacion de perfil de usuario para sesion
                    var profileData = new UserProfileSessionData
                    {
                        FullName = model.UserName,
                        Token    = token.access_token
                    };
                    ConnectionHelper.httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token.access_token);
                    this.Session["UserInfo"] = profileData;
                    return(RedirectToAction("Index", "Home"));

                    break;

                case System.Net.HttpStatusCode.BadRequest:
                    return(RedirectToAction("Login", "Home"));

                default:
                    return(RedirectToAction("Login", "Home"));
                }
            }
            return(RedirectToAction("Login", "Home"));
            //return View();



            //var response = await client.SendAsync(request);
            //response.EnsureSuccessStatusCode();

            //var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
            //var token = payload.Value<string>("access_token");



            //HttpResponseMessage response = ConnectionHelper.AuthorizeClient.PostAsJsonAsync("token", model).Result;
            //AuthorizationToken tokenItem = response.Content.ReadAsAsync<AuthorizationToken>().Result;



            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
        }