//admin signIn public static string SignIn(AdminSignIn loginDetails) { try { string hashpassword = HashPassword.ComputeSha256Hash(loginDetails.AdminToken); string qry = string.Format("SELECT 1 FROM Admin where AdminEmail='{0}' and AdminToken='{1}'", loginDetails.AdminEmail, hashpassword); //SqlConnection con = new SqlConnection(@"Data Source=ALEX-OVO-NATHAN\SQLSERVER2017DEV;Initial Catalog=Bank__DB;Integrated Security=True"); SqlCommand cmd = new SqlCommand(qry, con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { con.Close(); return("LOGIN SUCCESSFULLY"); } else { con.Close(); return("INVALID EMAIL OR PASSWORD"); } } catch (Exception ex) { return($"Check login details =>: \n{ex.Message}"); } }
public JsonResult CreateUser(UserViewModel userVM) { User user = AutoMapper.Mapper.Map <User>(userVM); user.DoB = DateTime.Today; user.Avatar = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/195612/chat_avatar_01.jpg"; Random random = new Random(); var newpass = random.Next(1000, 9000).ToString().Trim(); string emailAddress = user.Email; string[] emailSplitString = emailAddress.Split('@'); user.UserName = emailSplitString[0].Trim(); user.PassWord = HashPassword.ComputeSha256Hash(newpass); user.IsActive = true; db.Users.Add(user); db.SaveChanges(); string content = "<h1>Thông tin tài khoản là : </h1></br> "; content += "<h1> Username: "******"</h1></br> "; content += "<h1> Mật khẩu: " + newpass + "</h1></br> "; GuiEmail("Thông tin tài khoản", emailAddress, "*****@*****.**", "teamworkmastertogether@123", content); int userId = db.Users.Max(x => x.Id); ListFriend friend = new ListFriend() { UserId = userId }; db.ListFriends.Add(friend); db.SaveChanges(); return(Json(userVM, JsonRequestBehavior.AllowGet)); }
public JsonResult GetPassWord(FormCollection form) { // Lấy username và email từ form submit string username = form["Username"].ToString().Trim(); string email = form["Email"].ToString().Trim(); // Lấy ra username có tên và email thỏa mãn User user = db.Users.FirstOrDefault(s => s.UserName.Equals(username) && s.Email.Equals(email)); if (user != null) { Random random = new Random(); int length = 6; var str = ""; for (var i = 0; i < length; i++) { str += ((char)(random.Next(1, 26) + 64)).ToString(); } string emailAddress = user.Email; user.PassWord = HashPassword.ComputeSha256Hash(str); db.SaveChanges(); string content = "<h1>Thông tin tài khoản là : </h1></br> "; content += "<h1> Tên đăng nhập: " + username + "</h1></br> "; content += "<h1> Mật khẩu: " + str + "</h1></br> "; GuiEmail("Thông tin tài khoản", emailAddress, "*****@*****.**", "teamworkmastertogether@123", content); return(Json(new { status = 1 }, JsonRequestBehavior.AllowGet)); } return(Json(new { status = 0 }, JsonRequestBehavior.AllowGet)); }
public ActionResult Create([Bind(Include = "Id,StudentCode,StudentName,Email,ClassByGrade,Username,Password,Status,IsDeleted")] Student student) { if (db.Students.Any(x => x.Username == student.Username)) { //if username exists in DB before ViewBag.DuplicateError = "Username này đã tồn tại. Vui lòng nhập tên khác"; return(View(student)); } //if all validation is accepted if (ModelState.IsValid) { //hash password before adding to DB student.Password = HashPassword.ComputeSha256Hash(student.Password); db.Students.Add(student); db.SaveChanges(); //get student added ID int id = db.Students.Max(x => x.Id); //add user User user = new User() { Username = student.Username, Password = student.Password, Position = "Student", StudentId = id }; db.Users.Add(user); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(student)); }
public ActionResult SavePassword(int?id, PersonalDto personalDto) { var user = db.Users.FirstOrDefault(us => us.Id == id); user.PassWord = HashPassword.ComputeSha256Hash(personalDto.NewPassword); db.SaveChanges(); return(Json("Success", JsonRequestBehavior.AllowGet)); }
public ActionResult Edit([Bind(Include = "Id,StudentCode,StudentName,Email,ClassByGrade,Username,Password,Status,IsDeleted")] Student student) { if (ModelState.IsValid) { db.Entry(student).State = EntityState.Modified; student.Password = HashPassword.ComputeSha256Hash(student.Password); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(student)); }
public ActionResult Edit([Bind(Include = "Id,TeacherName,Email,Phone,Office,Username,Password,Status,IsDeleted")] Teacher teacher) { if (ModelState.IsValid) { db.Entry(teacher).State = EntityState.Modified; teacher.Password = HashPassword.ComputeSha256Hash(teacher.Password); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(teacher)); }
public ActionResult ConfirmPassword(int?id, PersonalDto personalDto) { var user = db.Users.FirstOrDefault(us => us.Id == id); personalDto.PassWord = HashPassword.ComputeSha256Hash(personalDto.PassWord); if (string.Compare(personalDto.PassWord, user.PassWord, true) == 0) { return(Json(new { isvalid = true }, JsonRequestBehavior.AllowGet)); } return(Json(new { isvalid = false }, JsonRequestBehavior.AllowGet)); }
public ActionResult Home(FormCollection form) { //lay ra username nhap vao tu form string Username = form["login-user"].ToString().Trim(); //lay ra password nhap vao tu form string Password = form["login-password"].ToString().Trim(); //tim user co username va password nhu vua nhap string hashedPassword = HashPassword.ComputeSha256Hash(Password); User user = db.Users.FirstOrDefault(u => u.Username.Equals(Username) && u.Password.Equals(hashedPassword)); if (user != null) { Session["User"] = user; if (user.Position.Equals("Teacher")) { //lay ra teacher theo id Teacher teacher = db.Teachers.FirstOrDefault(t => t.Id == user.TeacherId); //luu ten teacher vao session Session["Username"] = teacher.TeacherName.ToUpper(); //redirect den trang cua giao vien //actionName = Index, controllerName = Teacher, routeValue = Area Member return(RedirectToAction("ShowListClasses", "Teacher", new { area = "Member" })); } else if (user.Position.Equals("Student")) { //lay ra student theo id Student student = db.Students.FirstOrDefault(s => s.Id == user.StudentId); //luu ten teacher vao session Session["Username"] = student.StudentName.ToUpper(); //redirect den trang cua sinh vien //actionName = Index, controllerName = Student, routeValue = Area Member return(RedirectToAction("ShowListClass", "Student", new { area = "Member" })); } else { //luu ten admin vao session Session["Username"] = "******"; //redirect den trang cua admin //actionName = Index, controllerName = Home, routeValue = Area Admin return(RedirectToAction("Index", "Home", new { area = "Admin" })); } } else { Response.Write("<script>alert('Tên đăng nhập hoặc mật khẩu không chính xác')</script>"); } return(View()); }
public ActionResult Login(FormCollection form) { string username = form["username"].ToString().Trim(); string password = form["password"].ToString().Trim(); string hashedPassword = HashPassword.ComputeSha256Hash(password); Admin admin = db.Admins.FirstOrDefault(x => x.Username.Equals("admin") && x.Password.Equals("91b4d142823f7d20c5f08df69122de43f35f057a988d9619f6d3138485c9a203")); if (username == admin.Username && hashedPassword == admin.Password) { Session["username"] = admin.Username; return(RedirectToAction("Index")); } // Kiểm tra xem user có tồn tại không ViewBag.ThongBao = "Tên đăng nhập hoặc mật khẩu không chính xác"; return(View()); }
//check ability to save new student from excel public bool SaveStudent(string username, string password, string fullname, string email, string classbygrade, ClassSurveyDbContext db) { var result = false; try { //save student //if students exist before, then not import again //just import new student not exists in system if (db.Students.Where(x => x.Username.Equals(username)).Count() == 0) { var student = new Student(); student.Username = username; //hash password before adding student.Password = HashPassword.ComputeSha256Hash(password); student.StudentCode = username; student.StudentName = fullname; student.Email = email; student.ClassByGrade = classbygrade; db.Students.Add(student); db.SaveChanges(); int id = db.Students.Max(x => x.Id); //add new user User user = new User() { Username = username, Password = HashPassword.ComputeSha256Hash(password), Position = "Student", StudentId = id }; db.Users.Add(user); db.SaveChanges(); result = true; } } catch (Exception) { throw; } return(result); }
//check if we can save new teachers public bool SaveTeacher(string username, string password, string name, string email, ClassSurveyDbContext db) { var result = false; try { //if teacher not exists in system before //just add new teachers when they dont exist in system if (db.Teachers.Where(x => x.Username.Equals(username)).Count() == 0) { var teacher = new Teacher(); teacher.Username = username; //hash password before adding teacher.Password = HashPassword.ComputeSha256Hash(password); teacher.TeacherName = name; teacher.Email = email; db.Teachers.Add(teacher); db.SaveChanges(); int id = db.Teachers.Max(x => x.Id); //add new user User user = new User() { Username = username, Password = HashPassword.ComputeSha256Hash(password), Position = "Teacher", TeacherId = id }; db.Users.Add(user); db.SaveChanges(); result = true; } } catch (Exception) { throw; } return(result); }
//check ability to save new student from excel public bool SaveStudent(string fullname, string email, ChatDbcontext db) { var result = false; Random rd = new Random(); try { //save student //if students exist before, then not import again //just import new student not exists in system if (db.Users.Where(x => x.Email.Equals(email)).Count() == 0) { var user = new User(); user.Name = fullname.Trim(); user.Email = email.Trim(); user.PassWord = HashPassword.ComputeSha256Hash(1.ToString().Trim()); user.DoB = DateTime.Now; string[] emailSplitString = email.Split('@'); user.UserName = emailSplitString[0]; db.Users.Add(user); db.SaveChanges(); int userId = db.Users.Max(x => x.Id); ListFriend friend = new ListFriend() { UserId = userId }; db.ListFriends.Add(friend); db.SaveChanges(); result = true; } } catch (Exception) { throw; } return(result); }
public ActionResult ShowStudentInfo(FormCollection form) { //get user from session User user = Session["User"] as User; //input old password string password = form["oldpassword"].ToString(); //hash old password string hashedPassword = HashPassword.ComputeSha256Hash(password); //input new password string newPassword = HashPassword.ComputeSha256Hash(form["newpassword"]); //if user exists if (user != null) { //get student Student student = db.Students.FirstOrDefault(s => s.Id == user.StudentId); //type old password fail if (hashedPassword != user.Password) { Response.Write("<script>alert('Mật khẩu cũ không đúng. Vui lòng kiểm tra lại')</script>"); return(View(student)); } //rewrite new password fail else if (form["newpassword"].ToString().Trim() != form["repassword"].ToString().Trim()) { Response.Write("<script>alert('Mật khẩu mới không trùng nhau. Vui lòng kiểm tra lại')</script>"); return(View(student)); } //get user User u = db.Users.FirstOrDefault(us => us.Username == user.Username); u.Password = newPassword; student.Password = newPassword; db.SaveChanges(); Response.Write("<script>alert('Thay đổi mật khẩu thành công')</script>"); return(View(student)); } return(RedirectToAction("Index", "Authentication", new { area = "Authentication" })); }
public ActionResult Login(FormCollection form) { // Lấy username từ form string username = form["username"].ToString().Trim(); string password = form["password"].ToString().Trim(); string hashedPassword = HashPassword.ComputeSha256Hash(password); // Lấy user có username và password trùng với form submit User user = db.Users.FirstOrDefault(x => x.UserName.Trim().Equals(username) && x.PassWord.Trim().Equals(hashedPassword)); // Kiểm tra xem user có tồn tại không if (user != null) { if (user.IsActive == false) { ViewBag.ThongBao = "Tài khoản của bạn đã bị khóa"; return(View()); } Session["userName"] = user.UserName; return(RedirectToAction("Personal")); } ViewBag.ThongBao = "Tên đăng nhập hoặc mật khẩu không chính xác"; return(View()); }
public ActionResult Create([Bind(Include = "Id,TeacherName,Email,Phone,Office,Username,Password,Status,IsDeleted")] Teacher teacher) { if (ModelState.IsValid) { //hash password before adding teacher.Password = HashPassword.ComputeSha256Hash(teacher.Password); db.Teachers.Add(teacher); db.SaveChanges(); int id = db.Teachers.Max(t => t.Id); //add new user User user = new User() { Username = teacher.Username, Password = teacher.Password, Position = "Teacher", TeacherId = id }; db.Users.Add(user); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(teacher)); }
//Admin signup public static string AdminSignUpDB(AdminInfo adminDetails) { AdminFname = adminDetails.AdminFName; AdminLname = adminDetails.AdminLName; AdminEmail = adminDetails.AdminEmail; Code = PasswordCreation.GenerateCode(); Hashpwd = HashPassword.ComputeSha256Hash(Code); DateTime current = DateTime.Now; SqlCommand cmd = new SqlCommand(); try { if (AdminFname == "" || AdminLname == "") { throw new Exception(); } if (AdminEmail == "") { throw new Exception(); } if (!AdminEmail.Contains("@gmail.com")) { throw new Exception(); } cmd.Parameters.Clear(); cmd.Connection = con; cmd.CommandText = @"INSERT INTO Admin(AdminFirstName, AdminLastName, AdminEmail, AdminToken, Created_at) VALUES(@fname, @lname, @email, @token, @timestamp)"; cmd.Parameters.AddWithValue("@fname", AdminFname); cmd.Parameters.AddWithValue("@lname", AdminLname); cmd.Parameters.AddWithValue("@email", AdminEmail); cmd.Parameters.AddWithValue("@token", Hashpwd); cmd.Parameters.AddWithValue("@timestamp", current); con.Open(); cmd.ExecuteNonQuery(); con.Close(); try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); mail.To.Add(AdminEmail); mail.Subject = "Admin Info"; mail.Body = $"Your Access code: {Code} \n Use email and access code to login"; SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", Pwd); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); } catch (Exception ex) { return($"Failed from inner catch msg sending why => {ex.Message}"); } return($"Sucessfull Signup"); } catch (Exception ex) { return($"Failed from catch why => {ex.Message}"); } }
public static string CstCreateAcct(CstInfo newLoginDetails) { Code = PasswordCreation.GenerateCode(); Hashpwd = HashPassword.ComputeSha256Hash(Code); DateTime current = DateTime.Now; SqlCommand cmd = new SqlCommand(); SqlCommand cmdAct = new SqlCommand(); try { if (newLoginDetails.CstFName == "" || newLoginDetails.CstLName == "") { throw new Exception(); } if (newLoginDetails.CstEmail == "") { throw new Exception(); } if (!newLoginDetails.CstEmail.Contains("@gmail.com")) { throw new Exception(); } cmd.Parameters.Clear(); cmd.Connection = con; cmd.CommandText = @"INSERT INTO NewCstTable(cst_FirstName, cst_LastName, cst_Email, cst_Password, Created_acct_at) OUTPUT INSERTED.id_cst VALUES(@fname, @lname, @email, @token, @timestamp)"; cmd.Parameters.AddWithValue("@fname", newLoginDetails.CstFName); cmd.Parameters.AddWithValue("@lname", newLoginDetails.CstLName); cmd.Parameters.AddWithValue("@email", newLoginDetails.CstEmail); cmd.Parameters.AddWithValue("@token", Hashpwd); cmd.Parameters.AddWithValue("@timestamp", current); con.Open(); cstId = Convert.ToInt32(cmd.ExecuteScalar());//cmd.ExecuteNonQuery(); con.Close(); cmdAct.Parameters.Clear(); cmdAct.Connection = con; cmdAct.CommandText = string.Format("insert into AccountTable values(@acttype, @cstid, @actnum, @bal)"); cmdAct.Parameters.AddWithValue("@acttype", newLoginDetails.CstAcctType); cmdAct.Parameters.AddWithValue("@cstid", cstId); cmdAct.Parameters.AddWithValue("@actnum", PasswordCreation.GenerateAccount()); cmdAct.Parameters.AddWithValue("@bal", Convert.ToDouble(newLoginDetails.Balance)); con.Open(); cmdAct.ExecuteNonQuery(); try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); mail.To.Add(newLoginDetails.CstEmail); mail.Subject = "Cst Info"; mail.Body = $"Your Access code: {Code} \nUse your email {newLoginDetails.CstEmail} and access code to login"; SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", Pwd); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); } catch (Exception ex) { return($"CstFailed from inner catch msg sending why => {ex.Message}"); } return($"Customer sucessfull Signup => {cstId}"); } catch (Exception ex) { return($"CStFailed from catch why => {ex.Message}"); } finally { con.Close(); } }