public ActionResult Login(Users model)
        {
            if (!ModelState.IsValid) //Checks if input fields have the correct format
            {
                return
                    (View(model)); //Returns the view with the input values so that the user doesn't have to retype again
            }

            using (var db = new MainDbContext())
            {
                var emailCheck          = db.Users.FirstOrDefault(u => u.UserEmail == model.UserEmail);
                var getPassword         = db.Users.Where(u => u.UserEmail == model.UserEmail).Select(u => u.UserPass);
                var materializePassword = getPassword.ToList();
                var password            = materializePassword[0];
                var decryptedPassword   = CustomDecrypt.Decrypt(password);

                if (model.UserEmail != null && model.UserPass == decryptedPassword)
                //Checks whether the input is the same as those literals. Note: Never ever do this! This is just to demo the validation while we're not yet doing any database interaction
                // if (model.UserEmail == "*****@*****.**" & model.UserPass == "123456")
                {
                    var getName         = db.Users.Where(u => u.UserEmail == model.UserEmail).Select(u => u.FName);
                    var materializeName = getName.ToList();
                    var name            = materializeName[0];

                    var getUserId         = db.Users.Where(u => u.UserEmail == model.UserEmail).Select(u => u.UserId);
                    var materializeUserId = getUserId.ToList();
                    var userId            = materializeUserId[0];


                    var getUserTypeId         = db.Users.Where(u => u.UserEmail == model.UserEmail).Select(u => u.UserTypeId);
                    var materializeUserTypeId = getUserTypeId.ToList();
                    var UserTypeId            = materializeUserTypeId[0];

                    var getEmail         = db.Users.Where(u => u.UserEmail == model.UserEmail).Select(u => u.UserEmail);
                    var materializeEmail = getEmail.ToList();
                    var email            = materializeEmail[0];


                    var identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, name),
                        new Claim(ClaimTypes.Email, email),
                        new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
                        new Claim(ClaimTypes.Role, UserTypeId.ToString())

                        //  new Claim(ClaimTypes.n, userId.ToString())
                    }, "ApplicationCookie");

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

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

            ModelState.AddModelError("", "Invalid email or password");


            return(View(model)); //Should always be declared on the end of an action method
        }
Example #2
0
        public ActionResult Login(LoginViewModel model, string ReturnUrl = "")
        {
            string EncryptionKey = "SHA512";
            string message       = "";

            if (ModelState.IsValid)
            {
                using (EastMedDB db = new EastMedDB())
                {
                    var userexist = db.user.Where(a => a.UNI_ID == model.UNI_ID && a.IsActive == true).FirstOrDefault();
                    if (userexist != null)
                    {
                        if (string.Compare((model.Password.Trim()), CustomDecrypt.passwordDecrypt(userexist.PASSWORD, EncryptionKey)) == 0)
                        {
                            // In here 2 method has been used to save user login atraction to specific pages
                            // Sessions and cookies give as to control menus and specification for each user.
                            // Cookies to used authorized the application and protect to anonymous enter
                            // Cookies are encrypted in client site the avoid from the cookie attacks.

                            Session["RoleID"]         = userexist.FK_PRIVILEGE_ID;
                            Session["UserName"]       = userexist.FIRST_NAME + " " + userexist.LAST_NAME;
                            Session["UserID"]         = userexist.UNI_ID;
                            Session["UserDatabaseID"] = userexist.ID;
                            int    timeout   = model.RememberMe ? 525600 : 30; // 30 min to expire the cookie.
                            var    ticket    = new FormsAuthenticationTicket(model.UNI_ID, model.RememberMe, timeout);
                            string encrypted = FormsAuthentication.Encrypt(ticket);
                            var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                            cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                            cookie.HttpOnly = true;
                            Response.Cookies.Add(cookie);
                            if (Url.IsLocalUrl(ReturnUrl))
                            {
                                return(Redirect(ReturnUrl));
                            }
                            else
                            {
                                userexist.LAST_LOGINDATE = DateTime.Now;
                                db.user.Attach(userexist);
                                var entry = db.Entry(userexist);
                                entry.Property(x => x.LAST_LOGINDATE).IsModified = true;
                                db.SaveChanges();
                                return(RedirectToAction("Index", "Home"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "Invalid user/pass");
                            return(View());
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid user/pass");
                        return(View());
                    }
                }
            }
            ViewBag.Message = message;
            return(View());
        }
        public ActionResult Login(User model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = _context.Users.SingleOrDefault(u => u.UserName == model.UserName);
            var decryptedPassword = CustomDecrypt.Decrypt(user.PasswordHash);

            if (model.UserName != null && model.PasswordHash == decryptedPassword)
            {
                //ClaimsIdentity contains information (Claims) about the current user
                var identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, user.UserName),
                }, "ApplicationCookie");

                //Request is an object that reads HTTP request values
                //GetOwinContext Gets the owin context that links the middleware to the request
                var ctx = Request.GetOwinContext();

                //Authentication property links the middleware to an authentication to the app
                var authManager = ctx.Authentication;

                //SignIn gets the list of claims and uses to authenticate those values to be persisted throughout the app
                //SignIn sets the authentication cookie on the client.
                authManager.SignIn(identity);

                //return Redirect(GetRedirect(model.ReturnUrl));
                return(RedirectToAction("Index", "Book"));
            }

            ModelState.AddModelError("", "Invalid email or password");
            return(View(model));
        }
Example #4
0
        public ActionResult Login(Users model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Email or Password should not be empty");
                return(View(model));
            }

            using (var db = new MainDbContext())
            {
                var emailCheck  = db.Users.FirstOrDefault(u => u.Email == model.Email);
                var getPassword = db.Users.Where(u => u.Email == model.Email).
                                  Select(u => u.Password);
                var materializePassword = getPassword.ToList();
                if (materializePassword.Count() > 0)
                {
                    var password          = materializePassword[0];
                    var decryptedPassword = CustomDecrypt.Decrypt(password);

                    if (model.Email != null && model.Password == decryptedPassword)
                    {
                        var getName         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Name);
                        var materializeName = getName.ToList();
                        var name            = materializeName[0];

                        var getEmail         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Email);
                        var materializeEmail = getEmail.ToList();
                        var email            = materializeEmail[0];

                        var getCountry         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Country);
                        var materializeCountry = getCountry.ToList();
                        var country            = materializeCountry[0];

                        var identity = new ClaimsIdentity(new[] {
                            new Claim(ClaimTypes.Name, name),
                            new Claim(ClaimTypes.Email, email),
                            new Claim(ClaimTypes.Country, country),
                        }, "ApplicationCookie");

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

                        //return Redirect(GetRedirectUrl(model.ReturnUrl));
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }
            ModelState.AddModelError("", "Invalid Email or Password");
            return(View(model));
        }
Example #5
0
        public ActionResult Login(Users model)
        {
            if (!ModelState.IsValid) //Checks if input fields have the correct format
            {
                return(View(model)); //Returns the view with the input values so that the user doesn't have to retype again
            }

            using (var db = new MainDbContext())
            {
                var emailCheck          = db.Users.FirstOrDefault(u => u.Email == model.Email);
                var getPassword         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Password);
                var materializePassword = getPassword.ToList();
                var password            = materializePassword[0];
                var decryptedPassword   = CustomDecrypt.Decrypt(password);

                if (model.Email != null && model.Password == decryptedPassword)
                {
                    var getName         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Name);
                    var materializeName = getName.ToList();
                    var name            = materializeName[0];

                    var getCountry         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Country);
                    var materializeCountry = getCountry.ToList();
                    var country            = materializeCountry[0];

                    var getEmail         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Email);
                    var materializeEmail = getEmail.ToList();
                    var email            = materializeEmail[0];

                    var identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, name),
                        new Claim(ClaimTypes.Email, email),
                        new Claim(ClaimTypes.Country, country)
                    },
                                                      "ApplicationCookie");

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

                    authManager.SignIn(identity);

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

            ModelState.AddModelError("", "Invalid email or password");
            return(View(model)); //Should always be declared on the end of an action method
        }
Example #6
0
        public ActionResult Login(Users model)
        {
            if (!ModelState.IsValid) //Checks if input fields have the correct format
            {
                return(View(model)); //Returns the view with the input values so that the user doesn't have to retype again
            }

            using (var db = new MainDbContext())
            {
                var emailCheck = db.Users.FirstOrDefault(u => u.Email == model.Email);

                if (!String.IsNullOrEmpty(emailCheck.Email))
                {
                    var getUsername     = db.Users.Where(u => u.Email == model.Email).Select(u => u.Username);
                    var materializeName = getUsername.ToList();
                    var name            = materializeName[0];

                    var getPassword         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Password);
                    var materializePassword = getPassword.ToList();
                    var password            = materializePassword[0];
                    var decryptedPassword   = CustomDecrypt.Decrypt(password);

                    if (model.Email != null && model.Password == decryptedPassword)
                    {
                        var getEmail         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Email);
                        var materializeEmail = getEmail.ToList();
                        var email            = materializeEmail[0];

                        var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Name, name) }, "ApplicationCookie");

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

                        authManager.SignIn(identity);

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

            Warning("Invalid Email Address or Password", true);
            return(View(model));
        }
        public ActionResult Login(User model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (var db = new BettingSystemDbContext())
            {
                var usernameCheck       = db.Users.FirstOrDefault(u => u.Username == model.Username);
                var getPassword         = db.Users.Where(u => u.Username == model.Username).Select(u => u.Password);
                var materializePassword = getPassword.ToList();
                var password            = materializePassword.Count > 0? materializePassword[0] : "";
                var decryptedPassword   = CustomDecrypt.Decrypt(password);

                if (model.Username != null & model.Password == decryptedPassword)
                {
                    var getUsername     = db.Users.Where(u => u.Username == model.Username).Select(u => u.Username);
                    var materializeName = getUsername.ToList();
                    var name            = materializeName.Count > 0? materializeName[0] : "";
                    var getRoleStatus   = db.Users.Where(u => u.Username == model.Username).Select(u => u.IsAdmin);
                    var materializeRole = getRoleStatus.ToList();
                    var role            = materializeRole.Count > 0 ? materializeName[0] : "";

                    var identity = new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Name, name),
                        new Claim(ClaimTypes.Role, role)
                    }, "ApplicationCookie");

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

                    authManager.SignIn(identity);

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

            ModelState.AddModelError("", "Invalid username or password");
            return(View(model));
        }
Example #8
0
        public ActionResult Login(Models.User model)
        {
            using (var db = new MainDbContext())
            {
                var emailCheck          = db.UserDbContext.FirstOrDefault(u => u.UserEmail == model.Email);
                var getPassword         = db.UserDbContext.Where(u => u.UserEmail == model.Email).Select(u => u.UserPassword);
                var materializePassword = getPassword.ToList();
                if (emailCheck == null || materializePassword.Count == 0)
                {
                    ModelState.AddModelError("", "Invalid Email or Password");
                    return(View(model));
                }
                var password          = materializePassword[0];
                var decryptedPassword = CustomDecrypt.Decrypt(password);

                if (model.Email != null && model.Password == decryptedPassword)
                {
                    var getEmail = db.UserDbContext.Where(u => u.UserEmail == model.Email).Select(u => u.UserEmail);
                    model.IsAdmin = db.UserDbContext.Where(u => u.UserEmail == model.Email).Select(u => u.UserIsAdmin).FirstOrDefault();
                    var materializeEmail = getEmail.ToList();
                    var email            = materializeEmail[0];

                    var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, email) }, "ApplicationCookie");
                    Session["User"]   = identity.Name;
                    currentUserCookie = identity.Name;

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

                    authManager.SignIn(identity);

                    if (model.IsAdmin == true)
                    {
                        TempData["IsAdmin"] = "yes";
                        return(RedirectToAction("Index", "Admin"));
                    }
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View(model));
        }
        // GET: Users/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Users users = db.Users.Find(id);

            if (users == null)
            {
                return(HttpNotFound());
            }
            var decryptPassword = CustomDecrypt.Decrypt(users.UserPass);

            users.UserPass     = decryptPassword;
            ViewBag.UserTypeId = new SelectList(db.UserTypes, "UserTypeId", "UserType", users.UserTypeId);
            ViewBag.StatusId   = new SelectList(db.RStatus, "StatusId", "StatusName", users.StatusId);
            ViewBag.UStatusId  = new SelectList(db.UStatus, "UStatusId", "UStatusName", users.UStatusId);

            return(View(users));
        }
Example #10
0
        public ActionResult Login(users model)
        {
            using (var db = new MainDbContext())
            {
                var IdCheck     = db.users.FirstOrDefault(u => u.USER_ID == model.USER_ID);
                var getPassword = db.users.Where(u => u.USER_ID == model.USER_ID).Select(u => u.PASSWORD);

                var    materializePassword = getPassword.ToList();
                string password            = materializePassword[0];
                var    decryptedPassword   = CustomDecrypt.Decrypt(password);

                var    getUserNo = db.users.Where(u => u.USER_ID == model.USER_ID).Select(u => u.USER_NO).ToList();
                string userNo    = getUserNo[0].ToString();


                if (model.USER_ID != null && model.PASSWORD == decryptedPassword)
                {
                    Session["id"]      = model.USER_ID;
                    Session["User_No"] = userNo;
                    var identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, "Daeyong"),
                        new Claim(ClaimTypes.Email, "*****@*****.**"),
                        new Claim(ClaimTypes.Country, "Seoul")
                    }, "ApplicationCookie");

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

                    authManager.SignIn(identity);

                    ViewBag.Result = "Success";
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ViewBag.Result = "False";
                    return(View(model));
                }
            }
        }
Example #11
0
        public ActionResult Login(UserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                //handle the error message: return to the login page
                return(View(model));
            }

            using (var context = new MvcDbContext())
            {
                //fetch the user details from db and validate user
                string email    = model.Email;
                string password = model.Password;

                Users user = context.Users.FirstOrDefault(usr => usr.Email == email);
                if (user != null)
                {
                    var encryptedPassword = user.Password;
                    var decryptedPassword = CustomDecrypt.Decrypt(encryptedPassword);
                    if (password == decryptedPassword)
                    {
                        List <Claim> claims = new List <Claim> {
                            new Claim(ClaimTypes.Name, user.Name),
                            new Claim(ClaimTypes.Email, user.Email),
                            new Claim(ClaimTypes.Country, user.Country)
                        };

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

                        IOwinContext           owinContext = Request.GetOwinContext();
                        IAuthenticationManager authManager = owinContext.Authentication;
                        authManager.SignIn(identity);

                        string redirectUrl = GetRedirectUrl(model.ReturnUrl);
                        return(Redirect(redirectUrl));
                    }
                }
            }
            return(View(model));
        }
Example #12
0
        public ActionResult Login(UserViewModel model)
        {
            if (!ModelState.IsValid) //checks if input fields have the correct format and are valid
            {
                //if not, then return the same login view, with the inputs as is, so user doesn't have to retype them
                return(View(model));
            }

            using (var context = new MvcDbContext())
            {
                var user = model.Email != null?context.Users.FirstOrDefault(u => u.Email == model.Email) : null;

                if (user != null)
                {
                    var email             = user.Email;
                    var password          = user.Password;
                    var decryptedPassword = CustomDecrypt.Decrypt(password);
                    if (model.Email == email && model.Password == decryptedPassword)
                    {
                        //create a list of claims
                        List <Claim> claims = new List <Claim> {
                            new Claim(ClaimTypes.Name, user.Name),
                            new Claim(ClaimTypes.Email, user.Email),
                            new Claim(ClaimTypes.Country, user.Country)
                        };
                        //create a claims identity based on above claims, and instruct it to use cookie
                        var identity = new ClaimsIdentity(claims, "ApplicationCookie");

                        var owinContext = Request.GetOwinContext();
                        var authManager = owinContext.Authentication; //gets the authentication middleware functionality available on the current context
                        authManager.SignIn(identity);

                        string redirectUrl = GetRedirectUrl(model.ReturnUrl);
                        return(Redirect(redirectUrl));
                    }
                }
            }
            return(View(model)); //if email/psw entered by user is not correct, show the loginpage again
        }
Example #13
0
        public ClaimsIdentity IniciarSesion(string user, string password)
        {
            using (var db = new AccessDBContext())
            {
                var usuarioID = db.Usuarios.FirstOrDefault(u => u.UserId == user);
                if (usuarioID != null)
                {
                    var userPassword      = usuarioID.Password;
                    var decryptedPassword = CustomDecrypt.Decrypt(userPassword);
                    if (password == decryptedPassword)
                    {
                        var getName2 = usuarioID.Personas_con_Accesos.Personas_Naturales.Nombres + ' ' + usuarioID.Personas_con_Accesos.Personas_Naturales.Apellido_Paterno + ' ' + usuarioID.Personas_con_Accesos.Personas_Naturales.Apellido_Materno;
                        var permiso  = usuarioID.Permisos.Descripcion;

                        //cookie
                        var identity = new ClaimsIdentity(new[]
                        {
                            new Claim(ClaimTypes.Name, getName2),
                            new Claim(ClaimTypes.NameIdentifier, user),
                            new Claim(ClaimTypes.Role, permiso)
                        },
                                                          "ApplicationCookie");
                        //var ctx = Request.GetOwinContext();
                        //var authManager = ctx.Authentication;
                        //authManager.SignIn(identity);
                        return(identity);
                    }
                    else
                    {
                        throw new Exception("Password incorrecta...");
                    }
                }
                else
                {
                    throw new Exception("Usuario inexistente...");
                }
            }
        }
Example #14
0
        public ActionResult EditProfile()
        {
            using (var db = new MainDbContext())
            {
                string firstname  = User.Identity.Name;
                var    NurseModel = db.Nurse.FirstOrDefault(u => u.FirstName.Equals(firstname));

                var searchKeyAdd      = db.Nurse.Select(u => u.Key_Address);
                var materializeAddKey = searchKeyAdd.ToList();
                var KeyAdd            = materializeAddKey[0];
                var AddModel          = db.Address.FirstOrDefault(u => u.Id.Equals(KeyAdd));

                var searchKeyCon      = db.Nurse.Select(u => u.Key_Contact);
                var materializeConKey = searchKeyCon.ToList();
                var KeyCon            = materializeConKey[0];
                var ConModel          = db.Contact.FirstOrDefault(u => u.Id.Equals(KeyCon));

                var searchUserKey      = db.Nurse.Select(u => u.Key_Users);
                var materializeUserKey = searchUserKey.ToList();
                var KeyUser            = materializeUserKey[0];
                var UsersModel         = db.Users.FirstOrDefault(u => u.Id.Equals(KeyUser));

                var password = CustomDecrypt.Decrypt(UsersModel.Password);

                UsersModel.Password = password;

                var viewmodel = new NurseModel
                {
                    Contact = ConModel,
                    Address = AddModel,
                    Nurse   = NurseModel,
                    Users   = UsersModel
                };

                return(View(viewmodel));
            }
        }
Example #15
0
        public ActionResult Login(Users model)
        {
            if (!ModelState.IsValid) //Checks if input fields have the correct format
            {
                return(View(model)); //Returns the view with the input values so that the user doesn't have to retype again
            }

            using (var db = new MainDbContext())
            {
                var usernameCheck       = db.Users.FirstOrDefault(u => u.Username == model.Username);
                var getPassword         = db.Users.Where(u => u.Username == model.Username).Select(u => u.Password);
                var materializePassword = getPassword.ToList();
                var password            = materializePassword[0];
                var decryptedPassword   = CustomDecrypt.Decrypt(password);

                if (model.Username != null && model.Password == decryptedPassword)
                {
                    var getUsername         = db.Users.Where(u => u.Username == model.Username).Select(u => u.Username);
                    var materializeUsername = getUsername.ToList();
                    var username            = materializeUsername[0];

                    var getName         = db.Users.Where(u => u.Username == model.Username).Select(u => u.Name);
                    var materializeName = getName.ToList();
                    var name            = materializeName[0];

                    var getId         = db.Users.Where(u => u.Username == model.Username).Select(u => u.User_Id);
                    var materializeId = getId.ToList();
                    var userid        = materializeId[0];

                    var getEmail         = db.Users.Where(u => u.Username == model.Username).Select(u => u.Email);
                    var materializeEmail = getEmail.ToList();
                    var email            = materializeEmail[0];

                    var getKategori         = db.Users.Where(u => u.Username == model.Username).Select(u => u.Kategori);
                    var materializeKategori = getKategori.ToList();
                    var kategori            = materializeKategori[0];

                    var identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.NameIdentifier, username),
                        new Claim(ClaimTypes.Name, name),
                        new Claim(ClaimTypes.Email, email),
                        new Claim(ClaimTypes.Sid, userid.ToString()),
                        new Claim(ClaimTypes.Role, kategori)
                    },
                                                      "ApplicationCookie");

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

                    authManager.SignIn(identity);
                    if (kategori.Equals("1") || kategori.Equals("2"))
                    {
                        return(RedirectToAction("Index", "User"));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "StokPengecer"));
                    }
                }
            }

            ModelState.AddModelError("", "Invalid email or password");
            return(View(model));
        }
Example #16
0
        public ActionResult Login(Models.UserLoginInfo uli_cl)
        {
            //  check if there are any errors inside the form's values
            if (!ModelState.IsValid)
            {
                return(View(uli_cl));
            }

            using (var dbLogin = new MainDbContext())
            {
                var userLoginInfo = dbLogin.applicationUser.FirstOrDefault(u => u.UserName == uli_cl.username);

                if (userLoginInfo != null)
                {
                    var getPassword         = dbLogin.applicationUser.Where(u => u.UserName == uli_cl.username).Select(u => u.Password);
                    var materializePassword = getPassword.ToList();
                    var password            = materializePassword[0];
                    var decryptedPassword   = CustomDecrypt.Decrypt(password);

                    if (uli_cl.password == decryptedPassword && userLoginInfo.UserName == uli_cl.username)
                    {
                        var getUserFullName     = dbLogin.applicationUser.Where(u => u.UserName == uli_cl.username).Select(u => u.UserFullName);
                        var materializeFullName = getUserFullName.ToList();
                        var userFullName        = materializeFullName[0];

                        //  we need to store the employer somewhere
                        var getUserEmployer         = dbLogin.applicationUser.Where(u => u.UserName == uli_cl.username).Select(u => u.UserEmployer);
                        var materializeUserEmployer = getUserEmployer.ToList();
                        var userEmployer            = materializeUserEmployer[0];


                        var getUserRole         = dbLogin.applicationUser.Where(u => u.UserName == uli_cl.username).Select(u => u.UserRole);
                        var materializeUserRole = getUserRole.ToList();
                        var userRole            = materializeUserRole[0];


                        var getUserId         = dbLogin.applicationUser.Where(u => u.UserName == uli_cl.username).Select(u => u.Id);
                        var materializeUserId = getUserId.ToList();
                        var userId            = materializeUserId[0].ToString();


                        //  create an identity with name and role
                        var identity = new ClaimsIdentity(new[] {
                            new Claim(ClaimTypes.Name, userFullName),
                            new Claim(ClaimTypes.Role, userRole),
                            new Claim("userId", userId),
                            new Claim("clientName", userEmployer),
                        }, "ApplicationCookie");

                        //  actually login with identity
                        var ctx         = Request.GetOwinContext();
                        var authManager = ctx.Authentication;
                        authManager.SignIn(identity);

                        if (userRole == RoleNames.ROLE_ADMIN)
                        {
                            return(RedirectToAction("Index", "Admin"));
                        }
                        else if (userRole == RoleNames.ROLE_REGISTRAR)
                        {
                            return(RedirectToAction("Index", "Registrar"));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Client"));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid username or password");
                        return(View(uli_cl));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password");
                    return(View(uli_cl));
                }
            }
        }
        public ActionResult Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)    //check if input field are empty.
            {
                TempData["msg-type"] = "alert-warning";
                TempData["msg-head"] = "Warning";
                TempData["msg-des"]  = "Email/Password cannot be empty!!";
                return(View(model));
            }

            try
            {
                using (var db = new MainDbContext())
                {
                    var getPassword         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Password); //get password linked to the given email
                    var materializePassword = getPassword.ToList();

                    if (materializePassword.Count == 0) //count = 0 if the email is not available.
                    {
                        TempData["msg-type"] = "alert-warning";
                        TempData["msg-head"] = "Warning";
                        TempData["msg-des"]  = "Account does not exist!!";
                        return(View(model));
                    }

                    var password          = materializePassword[0];
                    var decryptedPassword = CustomDecrypt.Decrypt(password);

                    if (model.Email != null && model.Password == decryptedPassword
                        ) //check if email password combination is valid
                    {
                        var getFirstName         = db.Users.Where(u => u.Email == model.Email).Select(u => u.FirstName);
                        var materializeFirstName = getFirstName.ToList();
                        var firstname            = materializeFirstName[0];

                        var getLastName         = db.Users.Where(u => u.Email == model.Email).Select(u => u.LastName);
                        var materializeLastName = getLastName.ToList();
                        var lastname            = materializeLastName[0];

                        var getEmail         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Email);
                        var materializeEmail = getEmail.ToList();
                        var email            = materializeEmail[0];

                        var getCountry         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Country);
                        var materializeCountry = getCountry.ToList();
                        var country            = materializeCountry[0];

                        var identify = new ClaimsIdentity(new[] //creation of cookie.
                        {
                            new Claim(ClaimTypes.Name, firstname + " " + lastname),
                            new Claim(ClaimTypes.Email, email),
                            new Claim(ClaimTypes.Country, country),
                        }, "ApplicationCookie");

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

                        authManager.SignIn(identify);

                        return(RedirectToAction("Index", "Home")); //redirect to homepage
                    }
                    TempData["msg-type"] = "alert-warning";
                    TempData["msg-head"] = "Warning";
                    TempData["msg-des"]  = "Invalid Email or Password!!";
                    return(View(model));
                }
            }
            catch (ProviderIncompatibleException)
            {
                TempData["msg-type"] = "alert-danger";
                TempData["msg-head"] = "Oh Snap!!";
                TempData["msg-des"]  = "Unable to login!! Could not establish connection with server!!";
                return(View(model));
            }
            catch (EntityException)
            {
                TempData["msg-type"] = "alert-danger";
                TempData["msg-head"] = "Oh Snap!!";
                TempData["msg-des"]  = "Server Timeout!! Check your connection!!";
                return(View(model));
            }
        }
Example #18
0
        public ActionResult EditUser(string uniqueUserId)
        {
            if (uniqueUserId == "" || uniqueUserId == null)
            {
                return(HttpNotFound("Something went wrong. Please, contact the administration"));
            }
            try
            {
                SetRolesForViewBag();
                SetTypeOfActionWithRequestForm("Edit");

                string connectionStringCommon = CommonManager.ReturnNeededConnectionStringForCommonDatabase();

                // select only those people who exist in the DB
                string sqlToGetUsersInfo = @"SELECT userId, userUniqueDatabaseId, userPwd FROM tblUser 
                            WHERE userUniqueDatabaseId = @userUniqueDatabaseId";

                UserInfo ui = new UserInfo();

                using (SqlConnection conn = new SqlConnection(connectionStringCommon))
                {
                    conn.Open();
                    SqlCommand cmdToGetUsersInfo = new SqlCommand(sqlToGetUsersInfo, conn);
                    cmdToGetUsersInfo.Parameters.AddWithValue("@userUniqueDatabaseId", uniqueUserId);


                    using (SqlDataReader dt_ToGetUsersInfo = cmdToGetUsersInfo.ExecuteReader())
                    {
                        if (dt_ToGetUsersInfo.HasRows)
                        {
                            while (dt_ToGetUsersInfo.Read())
                            {
                                ui = new UserInfo
                                {
                                    userId       = dt_ToGetUsersInfo[0].ToString().TrimEnd(),
                                    uniqueUserId = dt_ToGetUsersInfo[1].ToString().TrimEnd(),
                                    userPwd      = CustomDecrypt.Decrypt(dt_ToGetUsersInfo[2].ToString().TrimEnd())
                                };
                            }
                        }
                    }
                }

                string connectionStringHotel = CommonManager.ReturnNeededConnectionStringForHotel();

                // select only those people who exist in the DB
                string sqlToGetMainUsersInfo = @"SELECT userType, userFullName, userEmail, userPhoneNumber FROM tblUserInformation 
                            WHERE userUniqueDatabaseId = @uniqueUserId";

                using (SqlConnection conn = new SqlConnection(connectionStringHotel))
                {
                    conn.Open();
                    SqlCommand cmdToGetUsersInfo = new SqlCommand(sqlToGetMainUsersInfo, conn);
                    cmdToGetUsersInfo.Parameters.AddWithValue("@uniqueUserId", ui.uniqueUserId);


                    using (SqlDataReader dt_ToGetUsersInfo = cmdToGetUsersInfo.ExecuteReader())
                    {
                        if (dt_ToGetUsersInfo.HasRows)
                        {
                            while (dt_ToGetUsersInfo.Read())
                            {
                                ui.userType        = dt_ToGetUsersInfo[0].ToString().TrimEnd();
                                ui.userFullName    = dt_ToGetUsersInfo[1].ToString().TrimEnd();
                                ui.userEmail       = dt_ToGetUsersInfo[2].ToString().TrimEnd();
                                ui.userPhoneNumber = dt_ToGetUsersInfo[3].ToString().TrimEnd();
                            }
                        }
                    }
                }
                return(View(ui));
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex);
                return(HttpNotFound("Something went wrong. Please, contact the administration"));
            }
        }
Example #19
0
        public ActionResult Login(Login model)
        {
            var isInternalUser = false;

            try
            {
                if (!ModelState.IsValid) //Checks if input fields have the correct format
                {
                    return(View(model)); //Returns the view with the input values so that the user doesn't have to retype again
                }


                using (var db = new CuddlyWombatEntities())
                {
                    var loggedInUser = (from u in db.Users
                                        where u.Email == model.Email
                                        select u).FirstOrDefault();

                    if (loggedInUser != null)
                    {
                        isInternalUser = true;
                        var decryptedPassword = CustomDecrypt.Decrypt(loggedInUser.Password);

                        if (decryptedPassword != model.Password)
                        {
                            ModelState.AddModelError("", "Invalid email or password");
                            return(View(model));
                        }

                        var identity = new ClaimsIdentity(new[] {
                            new Claim("IsInternalUser", isInternalUser.ToString()),
                            new Claim("UserID", loggedInUser.UserID.ToString()),
                            new Claim(ClaimTypes.Name, loggedInUser.Name),
                            new Claim(ClaimTypes.Email, loggedInUser.Email)
                        }, "ApplicationCookie");

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

                        ViewBag.IsInternalUser = Convert.ToBoolean(isInternalUser.ToString());

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        var loggedInCustomer = (from u in db.Customers
                                                where u.Email == model.Email
                                                select u).FirstOrDefault();

                        if (loggedInCustomer != null)
                        {
                            var decryptedPassword = CustomDecrypt.Decrypt(loggedInCustomer.Password);

                            if (decryptedPassword != model.Password)
                            {
                                ModelState.AddModelError("", "Invalid email or password");
                                return(View(model));
                            }

                            var identity = new ClaimsIdentity(new[] {
                                new Claim("IsInternalUser", isInternalUser.ToString()),
                                new Claim("UserID", loggedInCustomer.CustomerID.ToString()),
                                new Claim(ClaimTypes.Name, loggedInCustomer.GivenName + " " + loggedInCustomer.Surname),
                                new Claim(ClaimTypes.Email, loggedInCustomer.Email)
                            }, "ApplicationCookie");

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

                            ViewBag.IsInternalUser = Convert.ToBoolean(isInternalUser.ToString());

                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            ModelState.AddModelError("", "Invalid email or password");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Exception", ex.Message);
            }
            ViewBag.IsInternalUser = Convert.ToBoolean(isInternalUser.ToString());
            return(View(model)); //Should always be declared on the end of an action method
        }
        public ActionResult Login(LoginModel2 model)
        {
            if (!ModelState.IsValid)
            //if (model.CaptchaCodeText !=  Convert.ToString(Session["Captcha"])) //check if input == to captcha shown
            {
                if (Session["time"] == null)
                {
                    model.CapImage     = "data:image/png;base64," + Convert.ToBase64String(new Utility().VerificationTextGenerator());
                    model.CapImageText = Convert.ToString(Session["Captcha"]);

                    return(View("Sample", model));
                }
                else
                {
                    time = (int)Session["time"];
                    time++;
                    Session["time"] = time;
                    Response.Write("Wrong times: " + time.ToString());
                    if (time >= 3)
                    {
                        model.CapImage     = "data:image/png;base64," + Convert.ToBase64String(new Utility().VerificationTextGenerator());
                        model.CapImageText = Convert.ToString(Session["Captcha"]);

                        return(View("Sample", model));//Returns the view with the input values so that the user doesn't have to retype again
                    }
                } //Returns the view with the input values so that the user doesn't have to retype again

                /*if (Session["time"] == null)
                 *      {
                 *          Session["time"] = time + 1;
                 *          Response.Write("Wrong times: 1");
                 *      }
                 *      else
                 * {
                 *  time = (int)Session["time"];
                 *  time++;
                 *  Session["time"] = time;
                 *  Response.Write("Wrong times: " + time.ToString());
                 *  if (time >= 3)
                 *  {
                 *      model.CapImage = "data:image/png;base64," + Convert.ToBase64String(new Utility().VerificationTextGenerator());
                 *      model.CapImageText = Convert.ToString(Session["Captcha"]);
                 *
                 *      return View("Sample", model);//Returns the view with the input values so that the user doesn't have to retype again
                 *
                 *  }
                 * }*/
                return(View());
            }
            else
            {
                //MainDbContext db = new MainDbContext();
                using (var db = new MainDbContext())
                {
                    var usernameCheck       = db.Users.FirstOrDefault(u => u.Username == model.Users.Username);
                    var getPassword         = db.Users.Where(u => u.Username == model.Users.Username).Select(u => u.Password);
                    var materializePassword = getPassword.ToList();
                    if (materializePassword.Count != 0)
                    {
                        var password          = materializePassword[0];
                        var decryptedPassword = CustomDecrypt.Decrypt(password);
                        if (model.Users.Username != null && model.Users.Password == decryptedPassword)
                        {
                            var searchrole      = db.Role.Where(u => u.Id == usernameCheck.Key_Role).Select(u => u.RoleType);
                            var materializeRole = searchrole.ToList();
                            var role            = materializeRole[0];
                            var ctx             = Request.GetOwinContext();
                            var authManager     = ctx.Authentication;
                            if (role == "doctor")
                            {
                                var checkname       = db.Doctor.FirstOrDefault(u => u.Key_Users == usernameCheck.Id);
                                var getname         = db.Doctor.Where(u => u.Id == checkname.Id).Select(u => u.FirstName);
                                var materializeName = getname.ToList();
                                var name            = materializeName[0];

                                var identity = new ClaimsIdentity(new[] {
                                    new Claim(ClaimTypes.Name, name),
                                    new Claim(ClaimTypes.Role, role)
                                }, "ApplicationCookie");

                                authManager.SignIn(identity);
                                return(RedirectToAction("Index", "Doctor"));
                            }
                            else if (role == "FDR")
                            {
                                var checkname = db.FDR.FirstOrDefault(u => u.Key_Users == usernameCheck.Id);
                                //var getname = db.PersonInfo.Where(u => u.Id == checkname.Key_PersonInfo).Select(u => u.FirstName);
                                var getname         = db.FDR.Select(u => u.FirstName);
                                var materializeName = getname.ToList();
                                var name            = materializeName[0];
                                var identity        = new ClaimsIdentity(new[] {
                                    new Claim(ClaimTypes.Name, name),
                                    new Claim(ClaimTypes.Role, role)
                                }, "ApplicationCookie");


                                authManager.SignIn(identity);
                                return(RedirectToAction("Index", "FDR"));
                            }
                            else if (role == "nurse")
                            {
                                /*var checkname = db.Nurse.FirstOrDefault(u => u.Key_Users == usernameCheck.Id);
                                 * var getname = db.PersonInfo.Where(u => u.Id == checkname.Key_PersonInfo).Select(u => u.FirstName);
                                 * var materializeName = getname.ToList();
                                 * var name = materializeName[0];*/
                                var identity = new ClaimsIdentity(new[] {
                                    //new Claim(ClaimTypes.Name, name),
                                    new Claim(ClaimTypes.Role, role)
                                }, "ApplicationCookie");


                                authManager.SignIn(identity);
                                return(RedirectToAction("Index", "Nurse"));
                            }
                            else if (role == "administrator")
                            {
                                /*var checkname = db.Admin.FirstOrDefault(u => u.Key_Users == usernameCheck.Id);
                                 * var getname = db.PersonInfo.Where(u => u.Id == checkname.Key_PersonInfo).Select(u => u.FirstName);
                                 * var materializeName = getname.ToList();
                                 * var name = materializeName[0];*/
                                var identity = new ClaimsIdentity(new[] {
                                    //new Claim(ClaimTypes.Name, name),
                                    new Claim(ClaimTypes.Role, role)
                                }, "ApplicationCookie");


                                authManager.SignIn(identity);
                                return(RedirectToAction("Index", "Admin"));
                            }
                        }
                        if (Session["time"] == null)
                        {
                            Session["time"] = time + 1;
                            Response.Write("Wrong times: 1");
                        }
                        else
                        {
                            time = (int)Session["time"];
                            time++;
                            Session["time"] = time;
                            Response.Write("Wrong times: " + time.ToString());
                            if (time >= 3)
                            {
                                model.CapImage     = "data:image/png;base64," + Convert.ToBase64String(new Utility().VerificationTextGenerator());
                                model.CapImageText = Convert.ToString(Session["Captcha"]);

                                return(View("Sample", model));//Returns the view with the input values so that the user doesn't have to retype again
                            }
                        }
                    }
                    else
                    {
                        if (Session["time"] == null)
                        {
                            Session["time"] = time + 1;
                            Response.Write("Wrong times: 1");
                        }
                        else
                        {
                            time = (int)Session["time"];
                            time++;
                            Session["time"] = time;
                            Response.Write("Wrong times: " + time.ToString());
                            if (time >= 3)
                            {
                                model.CapImage     = "data:image/png;base64," + Convert.ToBase64String(new Utility().VerificationTextGenerator());
                                model.CapImageText = Convert.ToString(Session["Captcha"]);

                                return(View("Sample", model));//Returns the view with the input values so that the user doesn't have to retype again
                            }
                        }
                        //model.CapImage = "data:image/png;base64," + Convert.ToBase64String(new Utility().VerificationTextGenerator());
                        //model.CapImageText = Convert.ToString(Session["Captcha"]);
                        ModelState.AddModelError("", "Invalid username or password"); //Should always be declared on the end of an action method
                    }

                    return(View(model));
                }
            }
        }
Example #21
0
        public ActionResult Login(Users model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            using (var db = new MainDbContext())
            {
                var emailCheck          = db.Users.FirstOrDefault(u => u.Email == model.Email);
                var getPassword         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Password);
                var materializePassword = getPassword.ToList();
                var password            = materializePassword[0];
                var decryptedPassword   = CustomDecrypt.Decrypt(password);

                if (model.Email != null && model.Password == decryptedPassword)
                {
                    var getName         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Name);
                    var materializeName = getName.ToList();
                    var name            = materializeName[0];

                    var getIc = db.Users.Where(u => u.Email == model.Email).Select(u => u.Ic);
                    var materializeCountry = getIc.ToList();
                    var Ic = materializeCountry[0];

                    var getEmail         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Email);
                    var materializeEmail = getEmail.ToList();
                    var email            = materializeEmail[0];

                    var getRole         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Role);
                    var materializeRole = getRole.ToList();
                    var role            = materializeRole[0];

                    var getId         = db.Users.Where(u => u.Email == model.Email).Select(u => u.Id);
                    var materializeId = getId.ToList();
                    var Id            = materializeId[0].ToString();


                    var identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, name),
                        new Claim(ClaimTypes.Email, email),
                        new Claim(ClaimTypes.Sid, Ic),
                        new Claim(ClaimTypes.Role, role),
                        new Claim(ClaimTypes.NameIdentifier, Id)
                    }, "ApplicationCookie");

                    var claimsPrincipal = new ClaimsPrincipal(identity);
                    Thread.CurrentPrincipal = claimsPrincipal;

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

                    authManager.SignIn(identity);

                    Session["email"] = model.Email;

                    if (role == "Admin")
                    {
                        ViewBag.AlertMessageAdmin = "Welcome to RapidKL E-Ticketing";
                        return(RedirectToAction("Index", "Home"));
                    }
                    if (role == "User")
                    {
                        ViewBag.AlertMessageAdmin = "Welcome to RapidKL E-Ticketing";
                        return(RedirectToAction("UsersIndex", "Users"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Wrong Password or Email");
                }
            }


            return(View(model));
        }
Example #22
0
        public ActionResult ChangePassword(ChangePassword model, string ReturnUrl = "")
        {
            string message     = "";
            bool   Status      = false;
            string type        = "Success";
            var    userControl = new UserController();

            if (!userControl.checkPasswordStrengt(model.NewPassword))
            {
                message = "password does not match rules please include one uppercase letter, one number and one of these symbols !,@,#,$,%,^,&,*,?,_,~,-,£,(,)";
                Status  = true;
                type    = "Error";
            }
            else
            {
                var CurrentUserEmail = HttpContext.User.Identity.Name;
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    var user                  = dc.Users.Where(x => x.EmailID == CurrentUserEmail).FirstOrDefault();
                    var getPassword           = dc.Users.Where(u => u.EmailID == user.EmailID).Select(u => u.Password);
                    var materializePassword   = getPassword.ToList();
                    var password              = materializePassword[0];
                    var getCryptoOne          = dc.cryptokeys.Where(u => u.UserID == user.UserID).Select(u => u.cryptone);
                    var materializeCryptoOne  = getCryptoOne.ToList();
                    var CryptoOne             = materializeCryptoOne[0];
                    var getCryptoTwo          = dc.cryptokeys.Where(u => u.UserID == user.UserID).Select(u => u.crypttwo);
                    var materializeCryptoTwo  = getCryptoTwo.ToList();
                    var CryptoTwo             = materializeCryptoTwo[0];
                    var getCryptoTree         = dc.cryptokeys.Where(u => u.UserID == user.UserID).Select(u => u.crypttree);
                    var materializeCryptoTree = getCryptoTree.ToList();
                    var keyTree               = materializeCryptoTree[0];
                    var keyTwo                = CustomDecrypt.Decrypt(CryptoTwo, keyTree);
                    var keyOne                = CustomDecrypt.Decrypt(CryptoOne, keyTwo);
                    var decryptPassword       = CustomDecrypt.Decrypt(password, keyOne);

                    if ((string.Compare(model.Password, decryptPassword) == 0))
                    {
                        string NewkeyOne  = CustomEnrypt.RandomString(15);
                        string NewkeyTwo  = CustomEnrypt.RandomString(15);
                        string NewkeyTree = CustomEnrypt.RandomString(15);
                        user.Password = CustomEnrypt.Encrypt(model.NewPassword, NewkeyOne);
                        //user.Password = Crypto.Hash(user.Password);
                        user.ConfirmPassword = CustomEnrypt.Encrypt(model.ConfirmPassword, NewkeyOne);
                        var crypto = dc.cryptokeys.Where(x => x.UserID == user.UserID).FirstOrDefault();
                        crypto.cryptone  = CustomEnrypt.Encrypt(NewkeyOne, NewkeyTwo);
                        crypto.crypttwo  = CustomEnrypt.Encrypt(NewkeyTwo, NewkeyTree);
                        crypto.crypttree = NewkeyTree;
                        try
                        {
                            if (user.TempPasswordSet)
                            {
                                user.TempPasswordSet = false;
                                user.Failed_Logins   = 0;
                            }
                            dc.SaveChanges();
                            message = "Your password have been successfuly changed.";
                            Status  = true;
                        }
                        catch (DbEntityValidationException ex)
                        {
                            foreach (var entityValidationErrors in ex.EntityValidationErrors)
                            {
                                foreach (var validationError in entityValidationErrors.ValidationErrors)
                                {
                                    Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                                }
                            }
                        }
                    }
                    else
                    {
                        message = "Password does not match if Error continues contact administrator.";
                        Status  = true;
                        type    = "Error";
                    }
                }
            }

            ViewBag.Message = message;
            ViewBag.Status  = Status;
            ViewBag.Type    = type;
            return(View());
        }
Example #23
0
        /// <summary>
        /// Checks if a token is valid.
        /// </summary>
        /// <param name="token">string - generated either by GenerateToken() or via client with cryptojs etc.</param>
        /// <param name="ip">string - IP address of client, passed in by RESTAuthenticate attribute on controller.</param>
        /// <param name="userAgent">string - user-agent of client, passed in by RESTAuthenticate attribute on controller.</param>
        /// <returns>bool</returns>
        //public static List<string> IsTokenValid(string token, string ip, string userAgent)
        public static bool IsTokenValid(string token, string ip, string userAgent)
        {
            List <string> info = new List <string>();

            bool result = false;

            try
            {
                // Base64 decode the string, obtaining the token:username:timeStamp.
                string key = Encoding.UTF8.GetString(Convert.FromBase64String(token));

                // Split the parts.
                string[] parts = key.Split(new char[] { ':' });
                Console.WriteLine(parts);
                if (parts.Length == 3)
                {
                    // Get the hash message, username, and timestamp.
                    string   hash      = parts[0];
                    string   userId    = parts[1];
                    long     ticks     = long.Parse(parts[2]);
                    DateTime timeStamp = new DateTime(ticks);

                    info.Add("hash = " + hash);
                    info.Add("username = "******"userAgent = " + userAgent);
                    info.Add("ip = " + ip);

                    // Ensure the timestamp is valid.
                    bool expired = Math.Abs((DateTime.UtcNow - timeStamp).TotalMinutes) > _expirationMinutes;
                    info.Add("expired = " + expired);
                    if (!expired)
                    {
                        //
                        // Lookup the user's account from the db.
                        //
                        try
                        {
                            var    connectionString = CommonManager.ReturnNeededConnectionStringForCommonDatabase();
                            string sqlToCheckIfInsertionIsInProgress = "SELECT userPwd FROM tblUser WHERE userId = @userId AND ifRemoved='False'";
                            using (SqlConnection conn = new SqlConnection(connectionString))
                            {
                                conn.Open();
                                SqlCommand cmdToCheckIfInsertionIsInProgress = new SqlCommand(sqlToCheckIfInsertionIsInProgress, conn);
                                cmdToCheckIfInsertionIsInProgress.Parameters.AddWithValue("@userId", userId);

                                string decryptedUserPwd = (string)cmdToCheckIfInsertionIsInProgress.ExecuteScalar();
                                string userPwd          = CustomDecrypt.Decrypt(decryptedUserPwd);
                                string computedToken    = GenerateToken(userId, userPwd, ip, userAgent, ticks);

                                // Compare the computed token with the one supplied and ensure they match.
                                result = (token == computedToken);
                            }
                        }
                        catch (Exception e)
                        {
                            //Console.WriteLine(e);
                            return(false);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //Console.WriteLine(e);
                return(false);
            }
            return(result);
            //return info;
        }
        public ActionResult Login(UserLogin login, string ReturnUrl = "")
        {
            bool   Status  = false;
            string message = "";
            string type    = "Success";

            using (MyDatabaseEntities db = new MyDatabaseEntities())
            {
                //var v = dc.Users.Where(a => a.EmailID == login.EmailID).FirstOrDefault();

                var emailCheck            = db.Users.FirstOrDefault(u => u.EmailID == login.EmailID);
                var usr_id                = db.Users.Where(u => u.EmailID == login.EmailID).Select(u => u.UserID).FirstOrDefault();
                var getPassword           = db.Users.Where(u => u.EmailID == login.EmailID).Select(u => u.Password);
                var materializePassword   = getPassword.ToList();
                var password              = materializePassword[0];
                var getCryptoOne          = db.cryptokeys.Where(u => u.UserID == usr_id).Select(u => u.cryptone);
                var materializeCryptoOne  = getCryptoOne.ToList();
                var CryptoOne             = materializeCryptoOne[0];
                var getCryptoTwo          = db.cryptokeys.Where(u => u.UserID == usr_id).Select(u => u.crypttwo);
                var materializeCryptoTwo  = getCryptoTwo.ToList();
                var CryptoTwo             = materializeCryptoTwo[0];
                var getCryptoTree         = db.cryptokeys.Where(u => u.UserID == usr_id).Select(u => u.crypttree);
                var materializeCryptoTree = getCryptoTree.ToList();
                var keyTree               = materializeCryptoTree[0];
                var keyTwo                = CustomDecrypt.Decrypt(CryptoTwo, keyTree);
                var keyOne                = CustomDecrypt.Decrypt(CryptoOne, keyTwo);
                var decryptPassword       = CustomDecrypt.Decrypt(password, keyOne);
                //TODO: add decrypt af decryptkey using master decryptkey
                var user = db.Users.Where(u => u.EmailID == login.EmailID).FirstOrDefault();
                if (user != null && user.IsEmailVerified)
                {
                    if ((string.Compare(login.Password, decryptPassword) == 0) && !(user.Locked))
                    {
                        int    timeout   = login.RememberMe ? 525600 : 20; // 525600 min = 1 year
                        var    ticket    = new FormsAuthenticationTicket(login.EmailID, login.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);

                        if (user.TempPasswordSet)
                        {
                            return(RedirectToAction("ChangePassword", "UserSettings"));
                        }

                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    else
                    {
                        if (user.Failed_Logins < 3)
                        {
                            user.Failed_Logins++;
                            message = "Invalid email or password";
                            type    = "Error";
                            Status  = true;
                        }
                        else if (user.Failed_Logins == 3 || user.Locked)
                        {
                            user.Locked = true;
                            Status      = true;
                            type        = "Error";
                            message     = "To many log in attemtes you have been locked out please contact system admin to be unlocked.";
                        }
                        try
                        {
                            user.ConfirmPassword = user.Password;
                            db.SaveChanges();
                        }
                        catch (DbEntityValidationException ex)
                        {
                            foreach (var entityValidationErrors in ex.EntityValidationErrors)
                            {
                                foreach (var validationError in entityValidationErrors.ValidationErrors)
                                {
                                    Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (user == null)
                    {
                        message = "User does not exist ";
                        Status  = true;
                        type    = "Error";
                    }
                    if (!user.IsEmailVerified)
                    {
                        message = "Please verify your account";
                        Status  = true;
                        type    = "Error";
                    }
                }
            }
            ViewBag.Message = message;
            ViewBag.Status  = Status;
            ViewBag.Type    = type;
            return(View());
        }