示例#1
0
        public ActionResult LogIn(LogInModel model, string returnUrl)
        {
            if (ModelState.IsValid && AccountService.ValidateUser(model.Email, model.Password))
            {
                //Get the user
                var user = AccountService.GetUser(model.Email);

                //Call the authenticate
                AuthenticateUser(user.Id, user.FirstName, user.LastName, user.Email, user.FacebookId, user.AccessToken);

                //Check for return url
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                    !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                ModelState.AddModelError("*", "Sorry, the email or password is incorrect. Please try again.");
                return(View(model));
            }
        }
        public ActionResult LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            // Don't do this in production!
            if (model.Email == "*****@*****.**" && model.Password == "password")
            {
                var identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, "Ben"),
                    new Claim(ClaimTypes.Email, "*****@*****.**"),
                    new Claim(ClaimTypes.Country, "England")
                }, "ApplicationCookie");

                var ctx         = Request.GetOwinContext();
                var authManager = ctx.Authentication;

                authManager.SignIn(identity);

                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }

            // user authN failed
            ModelState.AddModelError("", "Invalid email or password");
            return(View());
        }
示例#3
0
        public ActionResult LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            //TODO:
            if (model.Email == "*****@*****.**" && model.Password == "admin")
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, "admin"),
                    new Claim(ClaimTypes.Email, "*****@*****.**"),
                    new Claim(ClaimTypes.Country, "Argentina"),
                };

                var identity = new ClaimsIdentity(claims, "ApplicationCookie");

                IOwinContext           context     = Request.GetOwinContext();
                IAuthenticationManager authManager = context.Authentication;

                authManager.SignIn(identity);
                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }
            ModelState.AddModelError("", "El email o la contraseña no son válidos.");
            return(View());
        }
示例#4
0
        public async Task <ActionResult> LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            var usermanager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(new ModelContext()));

            var user = usermanager.Find(model.Name, model.Password);

            if (user != null)
            {
                var identity = await usermanager.CreateIdentityAsync(
                    user, DefaultAuthenticationTypes.ApplicationCookie);

                var ctx         = Request.GetOwinContext();
                var authManager = ctx.Authentication;

                authManager.SignIn(identity);

                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }

            // user authN failed
            ModelState.AddModelError("", "Invalid Name or Password");

            return(View());
        }
示例#5
0
        public ActionResult Registration(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            var rees = userManager.Create(new AppUser {
                Email = model.Email, UserName = model.Email
            }, model.Password);

            return(RedirectToAction("Login", "Authorise"));

            var user = userManager.Find(model.Email, model.Password);

            if (user != null)
            {
                var identity = userManager.CreateIdentity(
                    user, DefaultAuthenticationTypes.ApplicationCookie);

                GetAuthenticationManager().SignIn(identity);
                return(RedirectToAction("Login", "Authorise"));
            }

            ModelState.AddModelError("", "Invalid email or password");
            return(View(model));
        }
示例#6
0
        public async Task <String> GetToken(String usuario, String password)
        {
            using (HttpClient client = new HttpClient())
            {
                //setup client
                client.BaseAddress = new Uri(this.url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(header);

                LogInModel login = new LogInModel();
                login.NombreUsuario = usuario;
                login.Contrasena    = password;
                String json = JsonConvert.SerializeObject(login);

                StringContent content =
                    new StringContent(json
                                      , System.Text.Encoding.UTF8, "application/json");
                String peticion = "api/Auth/Login";
                HttpResponseMessage response =
                    await client.PostAsync(peticion, content);

                if (response.IsSuccessStatusCode)
                {
                    String contenido =
                        await response.Content.ReadAsStringAsync();

                    var jObject = JObject.Parse(contenido);
                    return(jObject.GetValue("response").ToString());
                }
                else
                {
                    return(null);
                }
            }
        }
示例#7
0
        public IActionResult LogIn([FromBody] LogInModel logInModel)
        {
            var account = accountsRepository.GetAccountByUsername(logInModel.Username);

            if (account == null)
            {
                return(BadRequest(invalidAccountOrUserError));
            }
            var accountsPassword = accountsRepository.GetAccountHashedPassword(account.UserName);
            var isPasswordValid  = authenticationService.ComparePasswords(logInModel.Password, accountsPassword);

            if (!isPasswordValid)
            {
                return(BadRequest(invalidAccountOrUserError));
            }

            var returnAccount = new
            {
                account.EntityId,
                account.Name,
                account.Surname,
                account.Address,
                account.UserName,
                account.Role
            };

            return(Ok(returnAccount));
        }
示例#8
0
        public ActionResult Login(LogInModel login)
        {
            User user = new UserHandler().GetUserByLogIn(login.LoginId, login.Password);

            if (user != null)
            {
                if (Request.Browser.Cookies)
                {
                    if (login.RememberMe)
                    {
                        HttpCookie cook = new HttpCookie("login");
                        cook.Expires.AddDays(1);
                        cook.Values.Add("login", user.LoginId);
                        cook.Values.Add("Password", user.Password);
                        Response.SetCookie(cook);
                    }
                }
                Session.Add(WebUtil.CURRENT_USER, ModelHelper.tomodel(user));
                //string crl = Request.QueryString["c"];
                //string act = Request.QueryString["a"];
                //if (!string.IsNullOrEmpty("crl") && string.IsNullOrEmpty("act"));
                //{
                //    return RedirectToAction(crl, act);
                //}
                if (user.IsInRole(WebUtil.ADMIN_ROLE))
                {
                    return(RedirectToAction("home", "admin"));
                }
                else
                {
                    return(RedirectToAction("index", "home"));
                }
            }
            return(View());
        }
        protected void changeButton_Click(object sender, EventArgs e)
        {
            LogInManager logInManager = new LogInManager();
            LogInModel   aLogInModel  = new LogInModel();

            aLogInModel.Email            = emailTextBox.Text;
            aLogInModel.Password         = newPasswordTextBox.Text;
            aLogInModel.SecurityQuestion = securityQuestionList.Text;
            aLogInModel.Answer           = answerTextBox.Text;
            if (emailTextBox.Text != "" && newPasswordTextBox.Text != "" && confirmPasswordTextBox.Text != "" && securityQuestionList.Text != "Select a Question" && answerTextBox.Text != "")
            {
                string message = logInManager.ForgotPassword(aLogInModel);
                if (newPasswordTextBox.Text == confirmPasswordTextBox.Text)
                {
                    Response.Write("<script>alert('" + message + "')</script>");
                    Clear();
                }
                else
                {
                    mismatchLabel.Text      = "Password are Mismatched!";
                    mismatchLabel.ForeColor = Color.Red;
                }
            }
            else
            {
                Response.Write("<script>alert('Please fill all fields!')</script>");
            }
        }
示例#10
0
        public ActionResult LogIn(LogInModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    MigrateShoppingCart(model.UserName);

                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#11
0
        public IActionResult LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var userInDb = dbContext.Users.FirstOrDefault(u => u.Email == model.Email);

            if (userInDb == null)
            {
                ModelState.AddModelError("Password", "Invalid Email/Password");
                return(View());
            }
            var hasher = new PasswordHasher <LogInModel>();
            var result = hasher.VerifyHashedPassword(model, userInDb.Password, model.Password);

            if (result == 0)
            {
                ModelState.AddModelError("Password", "Invalid Email/Password");
                return(View());
            }
            HttpContext.Session.SetString("UserName", userInDb.FirstName);
            HttpContext.Session.SetInt32("UserId", userInDb.UserId);
            HttpContext.Session.SetInt32("Cart", getCartCount(userInDb.UserId));
            HttpContext.Session.SetInt32("isAdmin", isAdmin(userInDb.isAdmin));
            HttpContext.Session.SetString("Avatar", userInDb.AvatarPath);

            return(RedirectToAction("Index", "Home"));
        }
示例#12
0
        public ActionResult LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var result = UserInfoRepo.Login(model.UserName, model.Password);

            if (result.HasError)
            {
                ViewBag.Error = result.Message;
                return(View(model));
            }
            var userProfile = new UserProfile()
            {
                ID         = result.Data.ID,
                Name       = result.Data.Name,
                UserName   = result.Data.UserName,
                Email      = result.Data.Email,
                UserTypeID = result.Data.UserTypeID
            };
            var UserProfileJason = JsonConvert.SerializeObject(userProfile);

            FormsAuthentication.SetAuthCookie(UserProfileJason, false);
            return(RedirectToAction("Home", "Main"));
        }
示例#13
0
        public ActionResult LogIn(LogInModel model)
        {
            //try
            //{
            if (_userService.ValidateUserPassword(model.UserName, model.Password))
            {
                var user = _userService.GetOneUser(model.UserName);

                if (HttpContext.Session != null)
                {
                    HttpContext.Session["currentUserID"] = model.UserName;
                    HttpContext.Session["accessGroups"]  = _accessGroupService.GetAccessGroupsForUser(user);
                }

                if (user.MustChangePassword)
                {
                    return(RedirectToAction("ChangePassword", "LogIn"));
                }

                return(RedirectToAction("Index", "Home"));
            }
            TempData["Message"] = "Feil i brukernavn eller passord";
            return(RedirectToAction("LogIn", "LogIn"));
            //}
            //catch (Exception)
            //{
            //    TempData["Message"] = "Ukjent feil har oppstått";
            //    return RedirectToAction("LogIn", "LogIn");
            //}
        }
示例#14
0
        public async Task <IActionResult> LogIn(LogInModel model)
        {
            _logger.LogError("Method LogIn was called!");
            var response = await _identityService.LogInAsync(model.UserName, model.Password);

            return(Ok(new LoginResonse(Constants.TokenType, response.token, response.idToken, null)));
        }
示例#15
0
        public ActionResult Login(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            DAL    d   = new DAL();
            string img = "/Images/" + model.Username + "_profile.jpg";

            if (model.Password == d.GetUserPassword(model.Username))
            {
                var identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, d.GetUserScreenName(model.Username)),
                    new Claim(ClaimTypes.Sid, d.GetUserId(model.Username).ToString()),
                    new Claim(ClaimTypes.Role, d.GetUserRole(model.Username))
                },
                                                  "ApplicationCookie");

                var ctx         = Request.GetOwinContext();
                var authManager = ctx.Authentication;

                authManager.SignIn(identity);

                return(RedirectToAction("Home", "Home"));
            }

            // user authN failed
            ModelState.AddModelError("", "Invalid Username or Password");
            return(View());
        }
示例#16
0
        public ActionResult LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = userManager.Find(model.Email, model.Password);

            if (user != null)
            {
                var identity = userManager.CreateIdentity(
                    user, DefaultAuthenticationTypes.ApplicationCookie);
                GetAuthenticationManager().SignIn(identity);
                if (user.Roles.FirstOrDefault(x => x.RoleId == 1) != null)
                {
                    return(RedirectToAction("Index", "Admin"));
                }
                else
                {
                    return(RedirectToAction("Index", "Product"));
                }
                return(View(model));
            }

            return(RedirectToAction("WrongLogin"));
        }
示例#17
0
        public ActionResult UserLogin(LogInModel model)
        {
            LandingPage landingPageItems = new LandingPage();
            //landingPageItems = (LandingPage)Session["landingPageItems"];
            //Session["landingPageItems"] = landingPageItems;

            //model.Email
            //model.password
            //User user = new User();

            User         loggedInUser = new User();
            User_Queries user_Queries = new User_Queries();

            List <User> users = user_Queries.RetrieveUsersFromFirebase();

            foreach (User user in users)
            {
                if (user.email == model.Email && user.password == model.Password)
                {
                    loggedInUser = user;
                }
            }

            if (loggedInUser.email == null)
            {
                return(RedirectToAction("LogIn", "User"));
            }

            landingPageItems.User       = loggedInUser;
            landingPageItems.Courses    = user_Queries.RetrieveCoursesFromFirebase();
            landingPageItems.Posts      = user_Queries.RetrievePostsFromFirebase();
            Session["landingPageItems"] = landingPageItems;

            return(RedirectToAction("Index", "Home"));
        }
示例#18
0
 public async Task <ActionResult <TokenModel> > LogInAsync(
     [FromBody] LogInModel model,
     CancellationToken cancellationToken
     )
 {
     return(Ok(await _mediator.Send(new LogIn(model), cancellationToken)));
 }
示例#19
0
        public ActionResult LogIn(LogInModel model, string returnUrl)
        {
            ViewBag.DisplayError = true;
            string decodedUrl = "";

            if (VerifyLogin(model.UserName, model.Password, model.RememberMe))
            {

                int role = UserRoleData.GetByUserId(Authentication.CurrentUser.UserId).RoleId;
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    decodedUrl = Server.UrlDecode(returnUrl);
                    return Redirect(decodedUrl);
                }
                else
                {
                    if (role == 1 || role == 2)
                    {
                        return RedirectToAction("Index", "User");
                    }
                    else
                    {
                        return RedirectToAction("Dashboard", "Home");
                    }

                }
            }
            else { ViewBag.ErrorLogin = true; }
            ViewBag.ReturnURL = returnUrl;
            return View();
        }
示例#20
0
        public async Task <ActionResult> LogIn(LogInModel model)
        {
            var context     = Request.GetOwinContext();
            var authManager = context.Authentication;

            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = await userManager.FindAsync(model.Email, model.Password);

            if (user != null)
            {
                var identity = await userManager.CreateIdentityAsync(
                    user, DefaultAuthenticationTypes.ApplicationCookie);

                authManager.SignIn(identity);

                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }

            ModelState.AddModelError("", "Invalid email or password");
            return(View());
        }
示例#21
0
        public ActionResult Index(LogInModel logIn)
        {
            if (logIn.Username != null || logIn.Password != null)
            {
                string Username = logIn.Username;
                string Password = logIn.Password;
                if (UserLogIn(Username, Password) != null)
                {
                    return(RedirectToAction("GetList", "Home"));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }


            //Först:
            //Logga in
            //Authenticated = yes / no
            //Roles
            // key value
            //Authorization  bearer xxxxxxxxxx

            //string jsonregistercar = JsonConvert.SerializeObject(vehicleRequest);
            //var httpcontent = new StringContent(jsonregistercar, Encoding.UTF8, "application/json");
            //using (HttpClient client = new HttpClient())
            //{
            //    var response = client.PostAsync(url + "api/vehicle", httpcontent).Result;
            //}
            //UserLogIn();


            return(View());
        }
示例#22
0
        public ActionResult Login(string from)
        {
            if ((from ?? "").ToLower() == "logoff") LogOff();// Special Case: using an action named logoff creates complexity

            HttpCookie authCookie = Request.Cookies[Defaults.cookieName];
            LogInModel loginM = new LogInModel();

            #region If cookie present, then populate values from cookie

            if (authCookie != null)
            {
                try
                {// Set data as per cookie
                    //authCookie = HttpSecureCookie.Decode(authCookie, CookieProtection.Encryption);//HT: decode the encoded cookie
                    authCookie = new HttpCookie(Defaults.cookieName, Crypto.EncodeStr(authCookie.Value, false));
                    loginM.Email = authCookie.Values[Defaults.emailCookie];
                    loginM.Password = Crypto.EncodeStr(authCookie.Values[Defaults.passwordCookie], false);
                    loginM.RememberMe = true;
                }
                catch
                { /* BAD Cookie */loginM.RememberMe = false; }
            }

            #endregion

            #region Else, display Remember-Me check-box
            else
                loginM.RememberMe = false;
            #endregion

            return View(loginM);

            //Remember me issue with Forms Authentication
            //http://stackoverflow.com/questions/2452656/asp-net-mvc-remembermeits-large-please-dont-quit-reading-have-explained-the
        }
        public async Task <IActionResult> LogIn([FromBody] LogInModel model)
        {
            var user = await userManager.FindByNameAsync(model.Username);

            if (user != null && await userManager.CheckPasswordAsync(user, model.Password))
            {
                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };
                var signInKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MyVerylongSuperSecureKey"));

                var token = new JwtSecurityToken(
                    issuer: "http//taps.com",
                    audience: "http//taps.com",
                    expires: DateTime.Now.AddHours(1),
                    claims: claims,
                    signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signInKey, SecurityAlgorithms.HmacSha256)
                    );

                return(Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    expiration = token.ValidTo
                }));
            }
            return(Unauthorized());
        }
示例#24
0
 public Guid ReadLogIn(LogInModel model)
 {
     using (BusinessContext context = new BusinessContext())
     {
         return(context.UserBusiness.ReadLogIn(model.UserName, model.Password));
     }
 }
 public LogInViewModel(MainWidowViewModel containingVm)
 {
     this.containingVm = containingVm;
     logInModel        = new LogInModel();
     LogInUserCommand  = new LogInCommand(this);
     Message           = "";
 }
        /// <summary>
        /// Login test user analyzer using Rhino mock for handling cookies and authentication.
        /// This user has two different role regarding specieds observations.
        /// </summary>
        protected void LoginTestUserAnalyser()
        {
            // Mock account controller (Otherwise  accountController.HttpContext is null)
            //builder.InitializeController(accountController);

            // To handle login stubs must be created for  IFormsAuthenticationService
            //IFormsAuthenticationService formsAuthenticationServiceMock = MockRepository.GenerateStub<IFormsAuthenticationService>();
            //accountController.FormsService = formsAuthenticationServiceMock;

            //accountController.ControllerContext = GetAccountControllerContext();


            this.ShimControllerContextForLogin();

            //Log in test user
            LogInModel logInModel = new LogInModel();

            logInModel.UserName = AnalysisPortalTestSettings.Default.TestUserAnalyzerLoginName;
            logInModel.Password = AnalysisPortalTestSettings.Default.TestUserPassword;
            accountController.LogIn(logInModel, String.Empty);

            SessionHandler.Language = SessionHandler.UserContext.Locale.CultureInfo.Name;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(SessionHandler.Language);
            Thread.CurrentThread.CurrentCulture   = new CultureInfo(SessionHandler.Language);
        }
示例#27
0
        public async Task <IActionResult> Login(LogInModel model)
        {
            if (ModelState.IsValid)
            {
                UserDAO dAO = new UserDAO();
                int     id  = dAO.LogIn(model.Username, model.Password);

                if (id != -1)
                {
                    Utilizador user   = dAO.FindByUsername(model.Username);
                    var        claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, model.Username),
                        new Claim(ClaimTypes.Sid, id.ToString()),
                        new Claim(ClaimTypes.Role, user.Type.ToString())
                    };
                    ClaimsIdentity  userIdentity = new ClaimsIdentity(claims, "login");
                    ClaimsPrincipal principal    = new ClaimsPrincipal(userIdentity);

                    await HttpContext.SignInAsync(principal);

                    return(RedirectToAction("Index", "User", new { area = "" }));
                }
                ModelState.AddModelError("", "Wrong username and password");
            }

            return(View(model));
        }
示例#28
0
        //POST: /api/Users/Authenticate
        public IActionResult Authenticate(LogInModel model)
        {
            var user = _userService.Authenticate(model.Username, model.Password);

            if (user == null)
            {
                return(BadRequest("Log in details are incorrect."));
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.UTF8.GetBytes(_appSettings.JWT_Secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(new
            {
                Id = user.Id,
                Username = user.Username,
                Name = user.Name,
                Token = tokenString
            }));
        }
示例#29
0
 public Profile Authen(LogInModel loginModel)
 {
     return(this.Query
            .Where(p => p.Email.ToLower() == loginModel.Email || p.TaxNumber.ToLower() == loginModel.Email)
            .Where(p => p.Pin == loginModel.Pin)
            .FirstOrDefault());
 }
示例#30
0
        public async void LogIn_Click()
        {
            string enCryptedPassword = Cryptography.Encrypt(PASSWORD);

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(GlobalData.gblApiAdress);
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.Timeout = new TimeSpan(500000000000);
            HttpResponseMessage response = client.GetAsync("api/LogInAPI/GetUser?id=" + USERNAME + "&password="******"").Result;

            if (response.IsSuccessStatusCode)
            {
                data = JsonConvert.DeserializeObject <LogInModel>(await response.Content.ReadAsStringAsync());
                if (data != null)
                {
                    //var comp = Convert.ToInt32(App.Current.Properties["Company_Id"].ToString());
                    App.Current.Properties["Company_Id"] = data.COMPANY_ID;
                    App.Current.Properties["User_Id"]    = data.USER_ID;


                    HttpResponseMessage response3 = client.GetAsync("api/AccessRightAPI/GetAccessRights?EId=" + data.USER_ID + "").Result;
                    if (response.IsSuccessStatusCode)
                    {
                        data3 = JsonConvert.DeserializeObject <UserAccessModel[]>(await response3.Content.ReadAsStringAsync());
                        for (int i = 0; i < data3.Length; i++)
                        {
                            _ListGrid_Temp1.Add(new UserAccessModel
                            {
                                ACTION_CREATE = data3[i].ACTION_CREATE,
                                ACTION_DELETE = data3[i].ACTION_DELETE,
                                ACTION_VIEW   = data3[i].ACTION_VIEW,
                                APPROVE       = data3[i].APPROVE,
                                // Company_Id = data3[i].Company_Id,

                                EDIT          = data3[i].EDIT,
                                EXPT_TO_EXCEL = data3[i].EXPT_TO_EXCEL,
                                // ID = data3[i].ID,
                                IMORT_TO_EXCEL = data3[i].IMORT_TO_EXCEL,
                                MAILBACK       = data3[i].MAILBACK,
                                MESSAGE        = data3[i].MESSAGE,
                                MODULE_ID      = data3[i].MODULE_ID,
                                MODULE_NAME    = data3[i].MODULE_NAME,
                                NOTIFICATION   = data3[i].NOTIFICATION,
                                // ROLE_ID = data3[i].ROLE_ID,
                                // User_Id = data3[i].User_Id,
                                VERIFICATION = data3[i].VERIFICATION,
                            });
                        }
                    }
                    App.Current.Properties["AccessModuleByUser"] = _ListGrid_Temp1;
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Your Credentials is wrong");
                }
            }
        }
示例#31
0
        public IActionResult Login(LogInModel model)
        {
            if (!this.IsValidModel(model))
            {
                this.ShowError(LoginError);
                return(this.View());
            }

            if (!this.users.IsApproved(model.Email))
            {
                this.ShowError(UserIsNotApprovedError);
                return(this.View());
            }

            if (this.users.UserExists(model.Email, model.Password))
            {
                this.SignIn(model.Email);
                return(this.RedirectToHome());
            }
            else
            {
                this.ShowError(LoginError);
                return(this.View());
            }
        }
        public ActionResult LogIn(string returnUrl)
        {
            var model = new LogInModel
            {
                ReturnUrl = returnUrl
            };

            return View(model);
        }
示例#33
0
        public virtual ActionResult LogIn(string returnUrl)
        {
            string validatedReturnUrl = Uri.IsWellFormedUriString(returnUrl, UriKind.Relative) ? returnUrl : null;

            var model = new LogInModel
                            {
                                ReturnUrl = validatedReturnUrl
                            };

            return View(model);
        }
        public ActionResult LogIn(LogInModel model)
        {
            if (!_relyingParty.IsValidIdentifier(model.OpenId))
            {
                ModelState.AddModelError("loginIdentifier",
                            Resources.Errors.Account.InvalidIndentifier);
                return View();
            }

            return _relyingParty.CreateRequest(model.OpenId);
        }
        public async Task<ActionResult> LogIn(LogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            var user = await userManager.FindAsync(model.Email, model.Password);

            if (user != null)
            {
                await SignIn(user);
                return Redirect(GetRedirectUrl(model.ReturnUrl));
            }

            ModelState.AddModelError("", "Invalid email or password");
            return View();
        }
示例#36
0
 public ActionResult LogIn(LogInModel logInModel)
 {
     if (ModelState.IsValid)
     {
         var user = _userBl.GetUserByLoginAndPassword(logInModel.Login, logInModel.Password);
         if (user.UserName != null)
         {
             //Session["UserFullName"] = user.UserName + " " + user.LastName;
             //Session["UserLogin"] = user.Login;
             FormsAuthentication.SetAuthCookie(user.Login, false);
             return RedirectToAction("Index", "Home");
         }
         else
         {
             ModelState.AddModelError("", "Provided login or password is incorect");
             return View(logInModel);
         }
     }
     return View(logInModel);
 }
示例#37
0
        public ActionResult Login(LogInModel model, string ReturnUrl, bool? IsForgotPassword, string UserEmail)
        {
            if (IsForgotPassword.HasValue && IsForgotPassword.Value)
                return SendPassword(UserEmail, model);//SPECIAL CASE PROCESSING for Forgot password

            if (ModelState.IsValid)
            {
                vw_Users_Role_Org usr = new UserService().Login(model.Email, model.Password);
                //If the returned User object is not null or empty login is successfull
                if (usr != null && usr.ID > 0 && usr != new UserService().emptyView)
                {
                    Config.ConfigSettings = new SettingService().FetchSettings();//Initialize settings
                    FormsAuthentication.SetAuthCookie(usr.Email, model.RememberMe);//Set forms authentication!

                    #region Remember Me (add or remove cookie)

                    SetCookie(model);

                    #endregion

                    //Set session
                    _SessionUsr.setUserSession(usr);
                    _Session.RoleRights = new UserService().GetRoleRights(usr.RoleID);
                    //Log Activity
                    new ActivityLogService(ActivityLogService.Activity.Login).Add();

                    //Redirect to return url - if its valid
                    if (RedirectFromLogin(ref ReturnUrl))
                        return Redirect(ReturnUrl);
                    else//Go to the default url -  Dashboard?from=login
                        return RedirectToAction("List", "Dashboard");
                }
                else // Login failed
                    ModelState.AddModelError("", "The email and/or password provided is incorrect.");
            }

            LogOff();// To make sure no session is set until Login (or it'll go in Login HttpGet instead of Post)
            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public void LogInFailWithInvalidIndentifier()
        {
            var loginModel = new LogInModel {OpenId = ConnectionHelper.OpenId};
            var relyingParty = A.Fake<IAccountRelyingParty>();

            var accountController = ControllerLocator.GetAccountControllerForLoginTest(relyingParty);

            A.CallTo(() => relyingParty.IsValidIdentifier(ConnectionHelper.OpenId)).Returns(false);

            var result = accountController.LogIn(loginModel) as ViewResult;

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Error("loginIdentifier"), Is.Not.Null);
            Assert.That(result.Error("loginIdentifier"), Is.EqualTo(Resources.Errors.Account.InvalidIndentifier));

            A.CallTo(() => relyingParty.IsValidIdentifier(ConnectionHelper.OpenId)).MustHaveHappened();
        }
        public void TryLogInByRedirectingUserToRelyingParty()
        {
            var loginModel = new LogInModel { OpenId = ConnectionHelper.OpenId };
            // We don't care what the result is. We just want to check we get back the same object
            var redirectResult = new EmptyResult();
            var relyingParty = A.Fake<IAccountRelyingParty>();

            var accountController = ControllerLocator.GetAccountControllerForLoginTest(relyingParty);

            A.CallTo(() => relyingParty.IsValidIdentifier(ConnectionHelper.OpenId)).Returns(true);
            A.CallTo(() => relyingParty.CreateRequest(ConnectionHelper.OpenId)).Returns(redirectResult);

            var result = accountController.LogIn(loginModel);

            Assert.That(result, Is.Not.Null);
            Assert.That(result, Is.SameAs(redirectResult));

            A.CallTo(() => relyingParty.IsValidIdentifier(ConnectionHelper.OpenId)).MustHaveHappened();
            A.CallTo(() => relyingParty.CreateRequest(ConnectionHelper.OpenId)).MustHaveHappened();
        }
示例#40
0
 public ActionResult LogIn(LogInModel logInModel)
 {
     if (ModelState.IsValid)
     {
         if (FormsAuthentication.Authenticate(logInModel.userName, logInModel.password))
         {
             FormsAuthentication.SetAuthCookie(logInModel.userName, false);
             return RedirectToAction("SiteSettings", "AdminZone");
         }
         else
         {
             ViewBag.LoginFailed = true;
         }
     }
     return View(logInModel);
 }
示例#41
0
        //Remember Me (add or remove cookie)
        void SetCookie(LogInModel model)
        {
            bool remember = model.RememberMe;

            //Set Cookie (double encryption - encrypted pwd & encrypted cookie)
            HttpCookie authRememberCookie = new HttpCookie(Defaults.cookieName);
            authRememberCookie.Values[Defaults.emailCookie] = remember ? model.Email : "";
            authRememberCookie.Values[Defaults.passwordCookie] = remember ? Crypto.EncodeStr(model.Password, true) : "";
            authRememberCookie.Expires = remember ? DateTime.Now.AddHours(Config.RememberMeHours)
                : DateTime.Now.AddYears(-1);//to avoid any datetime diff
            /*HT: encode the cookie // Can't because of machine specific machine key - http://msdn.microsoft.com/en-us/library/ff649308.aspx#paght000007_webfarmdeploymentconsiderations
            authRememberCookie.Value = Encoding.Unicode.GetString(MachineKey.Protect(Encoding.Unicode.GetBytes(authRememberCookie.Value)));*/
            authRememberCookie.Value = Crypto.EncodeStr(authRememberCookie.Value, true);
            Response.Cookies.Add(authRememberCookie);
        }
示例#42
0
        public ActionResult LogIn()
        {
            var model = new LogInModel();

            return View(model);
        }
示例#43
0
        public ActionResult SendPassword(string Email, LogInModel model)
        {
            //Unable to get any other action to skip security check - nor can we have another view\page as we're using dialog
            ViewData["showSendPWD"] = true;
            ModelState.Clear();//clear any Login issues

            if (string.IsNullOrEmpty(Email))// ModelState.IsValid) - validate data explicitly
                ModelState.AddModelError("UserEmail", "Email is required field.");

            #region If data is valid and email is found, send email and set result viewstate
            else
            {
                string Pwd = new UserService().GetUserPWDByEmail(Email);
                bool oprSuccess = !string.IsNullOrEmpty(Pwd);

                ViewData["oprSuccess"] = oprSuccess;//Err msg handled in View
                if(oprSuccess)//Send email
                    MailManager.ForgotPwdMail(Email,Pwd, new SettingService().GetContactEmail());
            }
            #endregion

            LogOff();// To make sure no session is set until Login (or it'll go in Login HttpGet instead of Post)
            return View(model);
        }