Esempio n. 1
0
        public ActionResult Login(Logon logon)
        {
            // Verify the fields.
            if (ModelState.IsValid)
            {
                // Authenticate the user.
                if (UserManager.ValidateUser(logon, Response))
                {
                    // Redirect to the secure area.
                    return(RedirectToAction("Index", "Home"));

                    //if (string.IsNullOrWhiteSpace(logon.RedirectUrl))
                    //{
                    //    logon.RedirectUrl = Url.Action("Index", "Home");
                    //}

                    //status = "OK";
                    //string url = Url.Action("Index", "Home");
                    //return Json(new { success = true, url = url });


                    //return Json(new { RedirectUrl = logon.RedirectUrl, Status = status, isRedirect = true }, JsonRequestBehavior.AllowGet);
                }
            }
            return(PartialView("Login", new Logon()
            {
                ErrorMessage = "The username or password provided is incorrect."
            }));

            //return Json(new { RedirectUrl = logon.RedirectUrl, Status = status, isRedirect = false }, JsonRequestBehavior.AllowGet);
        }
Esempio n. 2
0
        public ActionResult Login(User user)
        {
            UserManager userManager = new UserManager(_db);
            User        loggedInUser;

            // Check username exists
            // Check username and password
            if (!userManager.UserExists(user.Username, out loggedInUser) ||
                !userManager.ValidateUser(user.Username, user.Password, out loggedInUser))
            {
                ModelState.AddModelError("Username", "Wrong username or password.");
                return(View("Index", user));
            }

            // Check if has at least one Approved role
            if (loggedInUser.Roles.Count() == 0)
            {
                ModelState.AddModelError("Username", "Pending Role to be approved.");
                return(View("Index", user));
            }

            var documents = new DocumentsFactory(_db, loggedInUser.Id);

            Session["user"]               = loggedInUser;
            Session["PendingDocuments"]   = documents.GetPending();
            Session["CompletedDocuments"] = documents.GetCompleted();

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 3
0
        public void ValidateUser_ThrowsException()
        {
            var username = string.Empty;
            var password = string.Empty;

            Assert.Throws <NullReferenceException>(() => userManager.ValidateUser(username, password));
        }
Esempio n. 4
0
        public JsonResult Find(string userName, string password)
        {
            UserManager manager = new UserManager();
            var user = manager.ValidateUser(userName, password);

            return Json(user, JsonRequestBehavior.AllowGet);
        }
Esempio n. 5
0
        private void metroButton1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(metroComboBoxUser.Text) == true || string.IsNullOrEmpty(metroTextBoxContraseña.Text) == true)
            {
                MessageBox.Show("Por Favor Inserte el nombre de Usuario y la Contraseña", "Sistema de Gestion Compras", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                UserManager umanager = new UserManager();


                if (umanager.ValidateUser(metroComboBoxUser.Text, metroTextBoxContraseña.Text) == 1)
                {
                    // MessageBox.Show("Usuario y Contraseña correcta", "Sistema de Gestion de Compras", MessageBoxButtons.OK, MessageBoxIcon.Information);



                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("Usuario o Contraseña incorrecta", "Sistema de Gestion Compras", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Refresh();
                }
            }
        }
 public ActionResult Login(UserViewModel user, string returnUrl)
 {
     if (UserManager.ValidateUser(user, Response))
     {
         return(Redirect(returnUrl ?? Url.Action("Index", "Product", new { area = "Products" })));
     }
     else
     {
         ViewBag.ErrorMessage = "Nije korektno korisničko ime ili lozinka";
         return(View());
     }
 }
Esempio n. 7
0
        public static bool IsUserVerified(string email, string password)
        {
            bool isVerified = false;

            UserManager userManager = UserManager.GetManager();

            if (userManager.ValidateUser(email, password))
            {
                isVerified = true;
            }
            return(isVerified);
        }
Esempio n. 8
0
 public IActionResult Login4(LoginDTO dto)
 {
     if (UserManager.ValidateUser(dto.Login, dto.Password) == true)
     {
         ViewBag.Msg = "Valid User!";
     }
     else
     {
         ViewBag.Msg = "Invalid User!";
     }
     return(View("Login", dto));
 }
Esempio n. 9
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            UserManager um         = new UserManager();
            String      userNameIn = userName.Value.Trim();
            String      passwordIn = pwd.Value.Trim();

            if (userNameIn != "" || passwordIn != "")
            {
                if (userNameIn.Length <= 80)
                {
                    if (passwordIn.Length <= 20)
                    {
                        bool user = um.ValidateUser(userNameIn, passwordIn);
                        if (user == false)
                        {
                            Response.Write("<script> alert(" + "'Datos Incorrectos'" + ") </script>");
                        }
                        else
                        {
                            User userSesssion = um.loadUserByUserName(userNameIn);
                            Session["userWithRol"] = userSesssion;
                            if (userSesssion.rol == 0)
                            {
                                Response.Redirect("~/LoadTemplate.aspx");
                            }
                            if (userSesssion.rol == 1)
                            {
                                Response.Redirect("~/LoadTemplate.aspx");
                            }
                            if (userSesssion.rol == 2)
                            {
                                Response.Redirect("~/LoadTemplate.aspx");
                            }
                        }
                    }
                    else
                    {
                        Response.Write("<script> alert(" + "'La contraseña no puede tener más de 20 caracteres'" + ") </script>");
                    }
                }
                else
                {
                    Response.Write("<script> alert(" + "'El nombre de usuario no puede tener más de 80 caracteres'" + ") </script>");
                }
            }
            else
            {
                Response.Write("<script> alert(" + "'Datos Vacíos'" + ") </script>");
            }
        }
Esempio n. 10
0
 public HttpResponseMessage GetValidatedUser(LoginUser loginUser)
 {
     UserManager userManager = new UserManager();
     try
     {
         var savedUser = userManager.ValidateUser(loginUser.UserName.Trim(), loginUser.Password.Trim());
         HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Accepted, loginUser);
         return response;
     }
     catch (Exception ex)
     {
         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
     }
 }
Esempio n. 11
0
        public ActionResult LoginUser(string email, string password)
        {
            if (_userManager.ValidateUser(email, password))
            {
                SignIn(email);
                return(Redirect("/"));
            }

            TempData["errors"] = new List <string>()
            {
                "Wrong email or password used."
            };
            return(RedirectToAction("Login"));
        }
Esempio n. 12
0
        public IActionResult ValidateUserLogin()
        {
            var request = this.HttpContext.Request;

            request.Query.TryGetValue("username", out var username);
            request.Query.TryGetValue("password", out var password);

            var res = _userManager.ValidateUser(username.ToString(), password.ToString());

            if (res == false)
            {
                return(StatusCode(StatusCodes.Status401Unauthorized, _contractBo.BuildBackendResponse <string>("Username e/ou password incorreto(s)", SOJStatusCode.SOJStatusCodes.Unauthorized)));
            }
            return(Ok(_contractBo.BuildBackendResponse <string>("Login efetuado com sucesso!", SOJStatusCode.SOJStatusCodes.OK, null)));
        }
Esempio n. 13
0
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                bool isValidUser = userManager.ValidateUser(model.Username, model.Password);
                if (isValidUser)
                {
                    Session["User"] = model;
                    return(RedirectToAction("Index", "Patient"));
                }

                ModelState.AddModelError("InvalidUser", "Invalid Credentials");
            }
            return(View(model));
        }
Esempio n. 14
0
        public ActionResult Update([Bind(Include = "UserName,Password,Email, City, FirstName, LastName, State,Zipcode, Address")] User _user)
        {
            if (ModelState.IsValid)
            {
                if (UserManager.User != null)
                {
                    User user = (from u in db.Users
                                 where u.UserId == UserManager.User.Id
                                 select u
                                 ).FirstOrDefault();
                    user.UserName  = _user.UserName;
                    user.Password  = _user.Password;
                    user.Email     = _user.Email;
                    user.City      = _user.City;
                    user.FirstName = _user.FirstName;
                    user.LastName  = _user.LastName;
                    user.State     = _user.State;
                    user.ZipCode   = _user.ZipCode;
                    user.Address   = _user.Address;

                    db.SaveChanges();

                    ModelState.Clear();

                    return(RedirectToAction("Index", "Category"));
                }
                else
                {
                    db.Users.Add(_user);
                    db.SaveChanges();

                    Logon logon = new Logon();
                    logon.Username = _user.UserName;
                    logon.Password = _user.Password;
                    if (_user.UserId > 0 && UserManager.ValidateUser(logon, Response))
                    {
                        ModelState.Clear();

                        return(RedirectToAction("Index", "Category"));
                    }
                }

                ModelState.Clear();
            }

            ViewBag.RegisterFailure = 1;    // errors ocured
            return(View("Index", _user));
        }
Esempio n. 15
0
        public async Task <ActionResult> Update([Bind(Include = "UserName,Password,Email, City, FirstName, LastName, State,Zipcode, Address")] User _user)
        {
            if (ModelState.IsValid)
            {
                AccountService service = new AccountService();

                if (UserManager.User != null)
                {
                    /*UserName
                     * Password,
                     * Email,
                     * City,
                     * FirstName,
                     * LastName,
                     * State,
                     * ZipCode,
                     * Address*/
                    // update user info
                    _user.UserId = UserManager.User.Id;
                    await service.updateUser(_user);

                    ModelState.Clear();

                    return(RedirectToAction("Index", "Category"));
                }
                else
                {
                    // add new user
                    User user = await service.addUser(_user);

                    // let that newly added user loged in automatically
                    Logon logon = new Logon();
                    logon.Username = user.UserName;
                    logon.Password = user.Password;
                    if (user.UserId > 0 && UserManager.ValidateUser(logon, Response))
                    {
                        ModelState.Clear();
                        return(RedirectToAction("Index", "Category"));
                    }
                }

                ModelState.Clear();
            }

            ViewBag.RegisterFailure = 1;    // errors ocured
            return(View("Index", _user));
        }
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            int userid;

            if (ModelState.IsValid && UserManager.ValidateUser(model.UserName, model.Password, 1, out userid))
            {
                User loggedUser = new DataTier.User.User()
                {
                    UserID = userid
                };
                loggedUser            = UserManager.GetUserByUserID(userid, 1);
                Session["LoggedUser"] = loggedUser;
                return(RedirectToLocal(returnUrl));
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return(View(model));
        }
Esempio n. 17
0
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                using (var db = new DataEntities())
                {
                    UserManager _userManager = new UserManager(new EntityRepository(db));
                    var         validateUser = _userManager.ValidateUser(context.UserName, context.Password);
                    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                    if (validateUser.Succeeded)
                    {
                        //if validating the user succeeded...

                        //aggregate the claims that makeup the token
                        var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                        //add any other relevant claim here...
                        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, validateUser.Result.UserId.ToString()));


                        //Create Extra properties
                        var props = new Dictionary <string, string>
                        {
                            { "UserId", validateUser.Result.UserId.ToString() },
                            { "Email", validateUser.Result.Email },
                            { "FirstName", validateUser.Result.FirstName },
                            { "LastName", validateUser.Result.LastName }//,
                            // { "ImageUrl", validateUser.Result.ImageUrl ?? "" }
                        };

                        context.Validated(new AuthenticationTicket(identity, new AuthenticationProperties(props)));
                    }
                    else
                    {
                        //if validating the user didnt succeed...

                        context.SetError("invalid_grant", validateUser.Message);
                        return;
                    }
                }
            }
Esempio n. 18
0
 private void loginMetroButton_Click(object sender, EventArgs e)
 {
     if (usernameTextBox.Text.Equals("") || passwordTextBox.Text.Equals(""))
     {
         MessageBox.Show("Username and password required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     else
     {
         try
         {
             User user = userManager.ValidateUser(usernameTextBox.Text, passwordTextBox.Text);
             if (user == null)
             {
                 this.passwordTextBox.Clear();
                 MessageBox.Show("Invalid username or password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             else if (user.Role1 == User.Role.manager)
             {
                 this.ResetTextFields();
                 new ManagerForm(user).Show();
                 this.Hide();
             }
             else if (user.Role1 == User.Role.admin)
             {
                 this.ResetTextFields();
                 new AdminForm(user).Show();
                 this.Hide();
             }
             else if (user.Role1 == User.Role.salesman)
             {
                 this.ResetTextFields();
                 new SalesmanForm(user).Show();
                 this.Hide();
             }
         }
         catch (Exception exception)
         {
             MessageBox.Show("Error ocured during loading database", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Esempio n. 19
0
        public HttpResponseMessage Post(LoginModel loginModel)
        {
            try
            {
                UserManager objManager = new UserManager();
                var         user       = objManager.ValidateUser(loginModel.Username, loginModel.Password);

                if (user == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Incorrect credentials."));
                }

                var    authModule = new AuthenticationModule();
                string token      = authModule.GenerateTokenForUser(user);

                return(Request.CreateResponse(HttpStatusCode.OK, new { Token = token, Expires = DateTime.UtcNow.AddDays(30) }));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Валидация при входе
        /// </summary>
        /// <param name="userName">Логин</param>
        /// <param name="password">Пароль</param>
        /// <returns>Результат валидации</returns>
        private bool ValidateLogOn(string userName, string password)
        {
            var manager = new UserManager(_userRepository, _roleRepository, _contactsRepository, _unitOfWork);

            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", "Вы должны ввести логин.");
                return(ModelState.IsValid);
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "Вы должны ввести пароль.");
                return(ModelState.IsValid);
            }
            if (!manager.ValidateUser(userName, password))
            {
                ModelState.AddModelError("_FORM", "Неправильный логин или пароль.");
                return(ModelState.IsValid);
            }

            return(ModelState.IsValid);
        }
Esempio n. 21
0
        public JsonResult Login(Logon logon)
        {
            string status = "The username or password provided is incorrect.";

            // Verify the fields.
            if (ModelState.IsValid)
            {
                // Authenticate the user.
                if (UserManager.ValidateUser(logon, Response))
                {
                    // Redirect to the secure area.
                    if (string.IsNullOrWhiteSpace(logon.RedirectUrl))
                    {
                        logon.RedirectUrl = "/";
                    }

                    status = "OK";
                }
            }

            return(Json(new { RedirectUrl = logon.RedirectUrl, Status = status }));
        }
        public ActionResult Register(UserViewModel user)
        {
            CreateUserRequest  request  = new CreateUserRequest();
            CreateUserResponse response = new CreateUserResponse();

            request.UserId   = Guid.NewGuid();
            request.Username = user.Username;
            request.Password = user.Password;
            request.Email    = user.Email;
            request.Role     = Role.User.ToString();
            response         = userService.CreateUser(request);
            if (response.Success)
            {
                UserManager.ValidateUser(user, Response);
                return(Redirect(Url.Action("Index", "Product", new { area = "Products" })));
            }
            else
            {
                ViewBag.ErrorMessage = "Nije korektno korisničko ime ili lozinka";
                return(View());
            }
        }
Esempio n. 23
0
        public ActionResult Login(LoginViewModel logon)
        {
            string status = "The username or password provided is incorrect.";

            // Verify the fields.
            if (ModelState.IsValid)
            {
                var result = Gmou.Web.Helpers.Converter.ModelConverter <LoginViewModel, LoginUser>(logon);
                // Authenticate the user.
                if (UserManager.ValidateUser(result, Response))
                {
                    // Redirect to the secure area.
                    if (string.IsNullOrWhiteSpace(logon.RedirectUrl))
                    {
                        logon.RedirectUrl = "/";
                    }

                    status = "OK";
                }
            }

            return(RedirectToActionPermanent("Index", "Admin"));
        }
        public ActionResult LogIn(FormCollection collection, string ReturnUrl)
        {
            try
            {
                //GetRealIpAddress();
                //int roleId = Convert.ToInt32(collection["RoleId"]);

                User   user     = new User();
                string userName = collection["userName"];
                string password = collection["Password"];
                user.Password = password;
                user.UserName = userName;

                //var userLocation = GetUserLocation();
                var userLocation = new UserLocation
                {
                    IPAddress = GetRealIpAddress(),
                };
                //var ltttt= collection["Latitude"];
                if (collection["Latitude"] != "")
                {
                    userLocation.Latitude  = Convert.ToDecimal(collection["Latitude"]);
                    userLocation.Longitude = Convert.ToDecimal(collection["Longitude"]);
                }

                bool validUser = _userManager.ValidateUser(user);

                if (validUser)
                {
                    userLocation.IsValidLogin = 1;
                    var model      = _userManager.GetUserByUserName(user.UserName);
                    var difference = (DateTime.Now - model.PasswordUpdateDate).TotalDays;
                    var anUser     = Mapper.Map <User, ViewUser>(model);
                    anUser.IsPasswordChangeRequired = difference > anUser.PasswordChangeRequiredWithin;
                    Session["Branches"]             = _iCommonManager.GetAssignedBranchesToUserByUserId(anUser.UserId).ToList();
                    Session["Roles"] = _userManager.GetAssignedUserRolesByUserId(anUser.UserId);
                    anUser.IsGeneralRequisitionRight = _iCommonManager.GetFirstApprovalPathByUserId(anUser.UserId);
                    anUser.IsApprovalRight           = _iCommonManager.GetFirstApprovalPathByApproverUserId(anUser.UserId);
                    Session["user"] = anUser;
                    int companyId = Convert.ToInt32(collection["companyId"]);
                    var company   = _iCompanyManager.GetById(companyId);
                    Session["CompanyId"] = companyId;
                    Session["Company"]   = company;
                    FormsAuthentication.SetAuthCookie(user.UserName, false);
                    var employee = _iEmployeeManager.GetEmployeeById(anUser.EmployeeId);
                    if (employee.EmployeeName != null)
                    {
                        anUser.EmployeeImage   = employee.EmployeeImage;
                        anUser.DesignationName = employee.DesignationName;
                        anUser.EmployeeName    = employee.EmployeeName;
                        anUser.UserDoB         = employee.DoB;
                    }
                    else
                    {
                        anUser.EmployeeImage = "Images/login_image.png";
                        anUser.EmployeeName  = userName;
                    }
                    anUser.IpAddress     = GetRealIpAddress();
                    anUser.MacAddress    = GetMacAddress().ToString();
                    anUser.LogInDateTime = DateTime.Now;


                    bool result = _userManager.ChangeLoginStatus(anUser, 1, userLocation);
                    Session.Timeout = 180;
                    if (anUser.IsPasswordChangeRequired)
                    {
                        return(RedirectToAction("ChangePassword", "Home", new { area = "CommonArea", id = anUser.UserId }));
                    }
                    switch (anUser.Roles)
                    {
                    case "Management":
                        return(RedirectToAction("Home", "Home", new { area = "Management" }));

                    default:
                        return(RedirectToAction("Goto", "LogIn", new { area = "" }));
                    }
                }
                ViewBag.Message   = "Invalid Login";
                ViewBag.Companies = _iCompanyManager.GetAll().ToList().OrderBy(n => n.CompanyId).ToList();
                return(View());
            }
            catch (Exception exception)
            {
                Log.WriteErrorLog(exception);
                return(PartialView("_ErrorPartial", exception));
            }
        }
        public ActionResult SWT(string realm, string redirect_uri, string deflate, string wrap_name, string wrap_password, string sf_domain = "Default", string sf_persistent = "false", string is_form = "false")
        {
            var         model = new LoginModel();
            UserManager um    = new UserManager(sf_domain);

            if (um.ValidateUser(wrap_name, wrap_password))
            {
                Session["tfa.authState"]     = 1;
                Session["tfa.realm"]         = realm;
                Session["tfa.redirect_uri"]  = redirect_uri;
                Session["tfa.deflate"]       = deflate;
                Session["tfa.wrap_name"]     = wrap_name;
                Session["tfa.sf_persistent"] = sf_persistent;

                UserProfileManager profileManager = UserProfileManager.GetManager();
                UserManager        userManager    = UserManager.GetManager();

                User user = userManager.GetUser(wrap_name);

                UserProfile profile = null;

                if (user != null)
                {
                    profile = profileManager.GetUserProfile <SitefinityProfile>(user);

                    string authyId = profile.GetValue <string>("AuthyId");

                    bool useTwoFactor = false;

                    if (!String.IsNullOrWhiteSpace(authyId))
                    {
                        useTwoFactor = true;

                        Session["tfa.authyId"] = authyId;
                    }

                    if (is_form == "false")
                    {
                        if (useTwoFactor)
                        {
                            return(Json(new { url = "/TFA/Authenticate/Verify" }));
                        }

                        return(Json(new { url = GetLoginUri() }));
                    }
                    else
                    {
                        if (useTwoFactor)
                        {
                            return(Redirect("/TFA/Authenticate/Verify"));
                        }

                        return(Redirect(GetLoginUri()));
                    }
                }
            }

            model.ProvidersList = GetProvidersList();

            ModelState.AddModelError("InvalidCredentials", "Incorrect Username/Password Combination");

            return(View("Login", model));
        }
Esempio n. 26
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        public ActionResult GoLogin(string userName, string pwd, string validateCode)
        {
            AjaxResult   result       = new AjaxResult();
            OperatorRule operatorRule = new OperatorRule();

#if DEBUG
            validateCode = Session["ValidateCode"].ToString();
#endif
            if (validateCode != Session["ValidateCode"].ToString())
            {
                result.Success = false;
                result.Message = "验证码输入错误。";
            }
            else
            {
                Logon logon = new Logon()
                {
                    Password = pwd, Username = userName
                };
                if (UserManager.ValidateUser(logon, Response))
                {
                    List <Ticket> currentTicketList = new List <Ticket>();
                    if (HttpContext.Cache["UserList"] != null)
                    {
                        currentTicketList = HttpContext.Cache["UserList"] as List <Ticket>;
                    }
                    if (currentTicketList.Count == 1)
                    {
                        //MyTicket.CurrentTicket = currentTicketList[0]; //唯一角色的用户直接进入系统
                        result.Success = true;
                        result.Url     = "/Home/Index";
                        //记录登录日志
                        LoginLog log = new LoginLog();
                        log.OperatorID = MyTicket.CurrentTicket.UserID;
                        log.CreateTime = DateTime.Now;
                        log.Type       = 1;
                        log.ID         = WebHelper.GetNewGuidUpper();
                        new LoginLogRule().Add(log);
                        return(Json(result, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        return(Json(currentTicketList, JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    result.Success = false;
                    result.Message = "用户名或者密码错误。";
                    return(Json(result, JsonRequestBehavior.AllowGet));
                }
                List <dynamic> userList = operatorRule.Login(userName, pwd);
                if (userList == null || userList.Count == 0)
                {
                    result.Success = false;
                    result.Message = "用户名或者密码错误。";
                }
                else
                {
                    List <Ticket> currentTicketList = new List <Ticket>();
                    foreach (dynamic t in userList)
                    {
                        if (currentTicketList.Count <Ticket>(ct => ct.GroupName == t.GROUPNAME) > 0)
                        {
                            continue;                            //同一用户多账号相同角色去重复
                        }
                        Ticket myTicket = new Ticket();
                        myTicket.DeptID       = t.DEPTID;
                        myTicket.DeptName     = t.DEPTNAME;
                        myTicket.EmployeeID   = t.EMPID;
                        myTicket.EmployeeName = t.EMPNAME;
                        myTicket.GroupID      = t.GROUPID;
                        myTicket.GroupName    = t.GROUPNAME;
                        myTicket.UserID       = t.ID;
                        myTicket.UserName     = t.OPERNAME;
                        myTicket.IsAdmin      = (t.ISADMIN == "1") ? true : false;
                        //myTicket.VoteList = new GroupVoteRule().GetOperVotes(t.GROUPID, t.ID);//获取权限列表
                        myTicket.VoteDic = new Dictionary <string, int>();
                        foreach (OperatorVote item in new GroupVoteRule().GetOperVotes(t.GROUPID, t.ID))
                        {
                            myTicket.VoteDic.Add(item.PoupID, item.VoteType);
                        }
                        //myTicket.CurrentOperator = operatorRule.GetModel(t.ID);
                        currentTicketList.Add(myTicket);
                    }
                    if (currentTicketList.Count == 1)
                    {
                        //MyTicket.CurrentTicket = currentTicketList[0];//唯一角色的用户直接进入系统
                        result.Success = true;
                        result.Url     = "/Home/Index";
                        //记录登录日志
                        LoginLog log = new LoginLog();
                        log.OperatorID = MyTicket.CurrentTicket.UserID;
                        log.CreateTime = DateTime.Now;
                        log.Type       = 1;
                        log.ID         = WebHelper.GetNewGuidUpper();
                        new LoginLogRule().Add(log);
                    }
                    else
                    {
                        Session["currentUserList"] = currentTicketList;                        //记录角色列表,等待用户选择
                        return(Json(currentTicketList, JsonRequestBehavior.AllowGet));
                    }
                }
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Esempio n. 27
0
        public string GetOverrideEmail(ref JobApplicationStatus status, ref ApplicantInfo applicantInfo, bool isSocialMedia = false)
        {
            string ovverideEmail = null;

            if (SitefinityHelper.IsUserLoggedIn()) // User already logged in
            {
                var currUser = SitefinityHelper.GetUserById(ClaimsManager.GetCurrentIdentity().UserId);
                if (currUser != null)
                {
                    Log.Write("User is already logged In " + currUser.Email, ConfigurationPolicy.ErrorLog);
                    return(currUser.Email);
                }
            }

            // User not looged in
            if (!string.IsNullOrEmpty(applicantInfo.Email))
            {
                Telerik.Sitefinity.Security.Model.User existingUser = SitefinityHelper.GetUserByEmail(applicantInfo.Email);

                if (existingUser != null)
                {
                    #region Entered Email exists in Sitefinity User list
                    Log.Write("User is already exists in portal " + existingUser.Email, ConfigurationPolicy.ErrorLog);
                    ovverideEmail = existingUser.Email;
                    // check user exists in the JXT next DB
                    var memberResponse = _blConnector.GetMemberByEmail(applicantInfo.Email);
                    if (memberResponse.Member == null)
                    {
                        UserProfileManager userProfileManager = UserProfileManager.GetManager();
                        UserProfile        profile            = userProfileManager.GetUserProfile(existingUser.Id, typeof(SitefinityProfile).FullName);
                        var fName = Telerik.Sitefinity.Model.DataExtensions.GetValue(profile, "FirstName");
                        var lName = Telerik.Sitefinity.Model.DataExtensions.GetValue(profile, "LastName");
                        JXTNext_MemberRegister memberReg = new JXTNext_MemberRegister
                        {
                            Email     = existingUser.Email,
                            FirstName = fName.ToString(),
                            LastName  = lName.ToString(),
                            Password  = existingUser.Password
                        };

                        if (_blConnector.MemberRegister(memberReg, out string errorMessage))
                        {
                            Log.Write("User created JXT next DB" + existingUser.Email, ConfigurationPolicy.ErrorLog);
                        }
                    }
                    return(ovverideEmail);

                    #endregion
                }
                else
                {
                    #region Entered email does not exists in sitefinity User list
                    var membershipCreateStatus = SitefinityHelper.CreateUser(applicantInfo.Email, applicantInfo.Password, applicantInfo.FirstName, applicantInfo.LastName, applicantInfo.Email, applicantInfo.PhoneNumber,
                                                                             null, null, true, true);
                    applicantInfo.IsNewUser = true;
                    if (membershipCreateStatus != MembershipCreateStatus.Success)
                    {
                        Log.Write("User is created in portal " + existingUser.Email, ConfigurationPolicy.ErrorLog);
                        status = JobApplicationStatus.NotAbleToCreateUser;
                        return(ovverideEmail);
                    }
                    else
                    {
                        //instantiate the Sitefinity user manager
                        //if you have multiple providers you have to pass the provider name as parameter in GetManager("ProviderName") in your case it will be the asp.net membership provider user
                        UserManager userManager = UserManager.GetManager();
                        if (userManager.ValidateUser(applicantInfo.Email, applicantInfo.Password))
                        {
                            //if you need to get the user instance use the out parameter
                            Telerik.Sitefinity.Security.Model.User userToAuthenticate = null;
                            SecurityManager.AuthenticateUser(userManager.Provider.Name, applicantInfo.Email, applicantInfo.Password, false, out userToAuthenticate);
                            if (userToAuthenticate == null)
                            {
                                status = JobApplicationStatus.NotAbleToLoginCreatedUser;
                                return(ovverideEmail);
                            }
                            else
                            {
                                ovverideEmail = userToAuthenticate.Email;
                            }
                        }
                    }
                    #endregion
                }
            }

            return(ovverideEmail);
        }
Esempio n. 28
0
        public ActionResult Index(LoginViewModel loginViewModel)
        {
            try
            {
                if (!string.IsNullOrEmpty(loginViewModel.Username) && !string.IsNullOrEmpty(loginViewModel.Password))
                {
                    var Username = loginViewModel.Username;
                    var password = EncryptionLibrary.EncryptText(loginViewModel.Password);

                    UserManager userManager = new UserManager();
                    var         result      = userManager.ValidateUser(Username, password);

                    if (result != null)
                    {
                        if (result.EmployeeID == 0 || result.EmployeeID < 0)
                        {
                            ViewBag.errormessage = "Invalid Username or Password";
                        }
                        else
                        {
                            var            RoleID         = result.RoleID;
                            AccountManager accountManager = new AccountManager();
                            var            accountList    = accountManager.GetAccounts();

                            Session["RoleID"]   = result.RoleID;
                            Session["Username"] = Convert.ToString(result.Username);
                            Session["FullName"] = result.FirstName + " " + result.LastName;
                            Session["UserID"]   = result.EmployeeID;
                            if (Convert.ToInt32(Session["RoleID"]) == 3)
                            {
                                var takeFirstAccount = accountList.OrderBy(x => x.Name).FirstOrDefault();
                                Session["Accounts"]  = new SelectList(accountList, "ID", "Name");
                                Session["AccountID"] = takeFirstAccount.ID;
                            }
                            else
                            {
                                accountList = accountList.Where(x => x.ID == result.AccountID).ToList();
                                var takeFirstAccount = accountList.Where(x => x.ID == result.AccountID).FirstOrDefault();
                                Session["Accounts"]  = new SelectList(accountList, "ID", "Name");
                                Session["AccountID"] = takeFirstAccount.ID;
                            }
                            return(RedirectToAction("Index", "Home"));
                            //if (RoleID == 1)
                            //{
                            //    Session["AdminUser"] = Convert.ToString(result.RegistrationID);

                            //    if (result.ForceChangePassword == 1)
                            //    {
                            //        return RedirectToAction("ChangePassword", "UserProfile");
                            //    }

                            //    return RedirectToAction("Dashboard", "Admin");
                            //}
                            //else if (RoleID == 2)
                            //{
                            //    if (!_IAssignRoles.CheckIsUserAssignedRole(result.RegistrationID))
                            //    {
                            //        ViewBag.errormessage = "Approval Pending";
                            //        return View(loginViewModel);
                            //    }

                            //    Session["UserID"] = Convert.ToString(result.RegistrationID);

                            //    if (result.ForceChangePassword == 1)
                            //    {
                            //        return RedirectToAction("ChangePassword", "UserProfile");
                            //    }

                            //    return RedirectToAction("Dashboard", "User");
                            //}
                            //else if (RoleID == 3)
                            //{
                            //    Session["SuperAdmin"] = Convert.ToString(result.RegistrationID);
                            //    return RedirectToAction("Dashboard", "SuperAdmin");
                            //}
                        }
                    }
                    else
                    {
                        ViewBag.errormessage = "Invalid Username or Password";
                        return(View(loginViewModel));
                    }
                }
                return(View(loginViewModel));
            }
            catch (Exception ex)
            {
                ViewBag.errormessage = ex.Message;
                logger.Error("EX" + ex);
                return(View());
            }
        }
 public User ValidateUser(string userName, string password)
 {
     User result = null;
     using (UserManager manager = new UserManager())
     {
         result = manager.ValidateUser(userName, password);
     }
     return result;
 }
        public ActionResult SWT(string realm, string redirect_uri, string deflate, string wrap_name, string wrap_password, string sf_domain = "Default", string sf_persistent = "false", string is_form = "false")
        {
            var model = new LoginModel();
            UserManager um = new UserManager(sf_domain);
            if (um.ValidateUser(wrap_name, wrap_password))
            {
                Session["tfa.authState"] = 1;
                Session["tfa.realm"] = realm;
                Session["tfa.redirect_uri"] = redirect_uri;
                Session["tfa.deflate"] = deflate;
                Session["tfa.wrap_name"] = wrap_name;
                Session["tfa.sf_persistent"] = sf_persistent;

                UserProfileManager profileManager = UserProfileManager.GetManager();
                UserManager userManager = UserManager.GetManager();

                User user = userManager.GetUser(wrap_name);

                UserProfile profile = null;

                if (user != null)
                {
                    profile = profileManager.GetUserProfile<SitefinityProfile>(user);

                    string authyId = profile.GetValue<string>("AuthyId");

                    bool useTwoFactor = false;

                    if (!String.IsNullOrWhiteSpace(authyId))
                    {
                        useTwoFactor = true;

                        Session["tfa.authyId"] = authyId;
                    }

                    if (is_form == "false")
                    {
                        if (useTwoFactor)
                        {
                            return Json(new { url = "/TFA/Authenticate/Verify" });
                        }

                        return Json(new { url = GetLoginUri() });
                    }
                    else
                    {
                        if (useTwoFactor)
                        {
                            return Redirect("/TFA/Authenticate/Verify");
                        }

                        return Redirect(GetLoginUri());
                    }
                }
            }

            model.ProvidersList = GetProvidersList();

            ModelState.AddModelError("InvalidCredentials", "Incorrect Username/Password Combination");

            return View("Login", model);
        }
Esempio n. 31
0
        //public ActionResult Login(String username, String password)
        public async Task <ActionResult> Login([Bind(Include = "Username,Password")] Logon logon)
        {
            if (ModelState.IsValid)
            {
                // Authenticate the user.
                if (UserManager.ValidateUser(logon, Response))
                {
                    /* move temporary shopping cart to DB */
                    string dateOfOpen = string.Empty;

                    // get tmp Cart in cookie
                    HttpCookie reqCartInfoCookies = HttpContext.Request.Cookies["CartInfo"];
                    if (reqCartInfoCookies != null)  // there is a temporary Cart in cookies
                    {
                        dateOfOpen = reqCartInfoCookies["DateOfOpen"].ToString();

                        Cart cart = null;

                        // get existing Cart
                        ShoppingService shoppingService = new ShoppingService();
                        cart = await shoppingService.getCart(UserManager.User.Id);

                        // there is no existing Shopping Cart for this user -> create new Shopping Cart
                        if (cart == null)
                        {
                            cart          = new Cart();
                            cart.UserId   = UserManager.User.Id;
                            cart.DateOpen = DateTime.Parse(dateOfOpen);

                            // add cart into system
                            cart = await shoppingService.addCart(cart);
                        }

                        HttpCookie reqIDListCookies = Request.Cookies["ProductDetailIDlist"];
                        if (reqIDListCookies != null)
                        {
                            string dataAsString = reqIDListCookies.Value;
                            if (!dataAsString.Equals(string.Empty))
                            {
                                List <int> listdata = new List <int>();
                                listdata = dataAsString.Split(',').Select(x => Int32.Parse(x)).ToList();
                                for (int i = 0; i < listdata.Count(); i++)
                                {
                                    HttpCookie reqCartItemCookies = Request.Cookies["CartItems[" + listdata[i].ToString() + "]"];
                                    if (reqCartItemCookies != null)
                                    {
                                        CartItem cookiesItem = new JavaScriptSerializer()
                                                               .Deserialize <CartItem>(reqCartItemCookies.Value);

                                        // get Cart Item of this ProductDetailId in DB
                                        int            productDetailId = listdata[i];
                                        CartDetailItem detail          = await shoppingService
                                                                         .getCartItemByCartIdAndProductDetailsId(cart.CartId, productDetailId);

                                        if (detail == null)
                                        {
                                            detail = new CartDetailItem();

                                            detail.UserId           = UserManager.User.Id;
                                            detail.Amount           = (short)cookiesItem.Amount;
                                            detail.ExtendedPrice    = cookiesItem.Price;
                                            detail.Type             = 0;
                                            detail.ProductDetailsId = listdata[i];
                                            detail.CartId           = cart.CartId;

                                            // add into system
                                            await shoppingService.addCartItem(detail);
                                        }
                                        else
                                        {
                                            detail.Amount += (short)cookiesItem.Amount;

                                            // update into system
                                            await shoppingService.updateQuantity(detail);
                                        }

                                        /* remove cart item of this ProductDetailId in cookies */
                                        var respCartItemscookies = new HttpCookie("CartItems[" + listdata[i].ToString() + "]");
                                        respCartItemscookies.Expires = DateTime.Now.AddDays(-1D);
                                        Response.Cookies.Add(respCartItemscookies);
                                    }
                                }

                                /* update productDetailID list in cookies */
                                HttpCookie respIDListCookies = new HttpCookie("ProductDetailIDlist", "")
                                {
                                    Expires = DateTime.Now.AddDays(1)
                                };
                                HttpContext.Response.Cookies.Add(respIDListCookies);
                            }
                        }
                    }

                    // Redirect to the secure area.
                    return(RedirectToAction("Index", "Category"));
                }
            }

            ViewBag.LoginFailure = 1;
            return(View());
        }