public ActionResult Create(NewUser newUser) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { string dateEdited = DateTime.Now.ToString("yyyy-MM-dd"); var encryptedPassword = CustomEncrypt.Encrypt(newUser.Password); var user = db.NewUsers.Create(); user.FirstName = newUser.FirstName; user.LastName = newUser.LastName; user.Email = newUser.Email; user.Password = encryptedPassword; user.DateEdited = dateEdited; db.NewUsers.Add(user); db.SaveChanges(); } } else { ModelState.AddModelError("", "Missing some field(s) value"); } return(RedirectToAction("Index")); }
public static CaptchaModel GetCaptchaModel(string name) { var model = new CaptchaModel(); if (name != "") { model.ID = name; } else { model.ID = "captcha"; } // This Captcha code was extracted from: // http://www.stefanprodan.eu/2012/01/user-friendly-captcha-for-asp-net-mvc/ var rand = new Random((int)DateTime.Now.Ticks); // Generate new question int a = rand.Next(0, 9); int b = rand.Next(0, 9); int c = rand.Next(0, 9); int d = rand.Next(0, 9); int e = rand.Next(0, 9); var captcha = string.Format("{0} {1} {2} {3} {4}", a, b, c, d, e); using (var mem = new MemoryStream()) using (var bmp = new Bitmap(130, 30)) using (var gfx = Graphics.FromImage(bmp)) { gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; gfx.SmoothingMode = SmoothingMode.AntiAlias; gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height)); // Add noise int i, r, x, y; Pen pen = new Pen(Color.Yellow); for (i = 1; i < 10; i++) { pen.Color = Color.FromArgb((rand.Next(0, 255)), (rand.Next(0, 255)), (rand.Next(0, 255))); r = rand.Next(0, (130 / 3)); x = rand.Next(0, 130); y = rand.Next(0, 30); gfx.DrawEllipse(pen, x - r, y - r, r, r); } // Add question gfx.DrawString(captcha, new Font("Tahoma", 16), Brushes.Gray, 2, 3); // Render as Png bmp.Save(mem, ImageFormat.Png); model.Image = Convert.ToBase64String(mem.GetBuffer()); model.EncryptedValue = CustomEncrypt.Encrypt(captcha.Replace(" ", "")); } return(model); }
public ActionResult Registration(UserViewModel model) { if (ModelState.IsValid) { var password = model.Password; var encryptedPassword = CustomEncrypt.Encrypt(password); using (var context = new MvcDbContext()) { var userAlreadyExists = context.Users.Any(usr => usr.Email == model.Email); if (userAlreadyExists) { return(RedirectToAction("Registration")); } Users user = context.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.Name = model.Name; user.Country = model.Country; context.Users.Add(user); context.SaveChanges(); } return(RedirectToAction("Login", "Auth")); } ModelState.AddModelError("", "One or more fields are invalid"); return(View()); }
public ActionResult Registration(users model) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { { var encryptedPassword = CustomEncrypt.Encrypt(model.PASSWORD); var user = db.users.Create(); user.USER_NO = model.USER_NO; user.USER_ID = model.USER_ID; user.PASSWORD = encryptedPassword; user.COUNTRY = model.COUNTRY; user.NAME = model.NAME; user.MAIL = model.MAIL; user.USER_STATUS = "A10"; db.users.Add(user); db.SaveChanges(); } return(RedirectToAction("Login", "auth")); } } else { ModelState.AddModelError("", "One or more fields have been"); } return(View()); }
// Initialize the First admin protected override void Seed(EastMed.Data.Model.EastMedDB context) { string EncryptionKey = "SHA512"; string UserName = "******"; string LastName = "Admin"; string PasswordEnc = "eastmedAdmin"; string UNIver_ID = "100000000"; context.user.AddOrUpdate(u => u.UNI_ID, new user { UNI_ID = UNIver_ID, FIRST_NAME = UserName, LAST_NAME = LastName, PASSWORD = CustomEncrypt.passwordEncrypt(PasswordEnc, EncryptionKey), TITLE = "Mr.Admin", PHONE = "000000000", FK_PRIVILEGE_ID = 5, FK_LOCATION_ID = 0, IsActive = true, CREATED_DATE = DateTime.Now, EMAIL = "*****@*****.**", }); context.SaveChanges(); }
public ActionResult Registration(Users model) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { var queryUser = db.Users.FirstOrDefault(u => u.Email == model.Email); if (queryUser == null) { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.Country = model.Country; user.Name = model.Name; db.Users.Add(user); db.SaveChanges(); } else { return(RedirectToAction("Registration")); } } } else { ModelState.AddModelError("", "One or more fields have been"); } return(View()); }
public ActionResult Add(UserVM model, int?LocationID) { var SessionControl = Convert.ToInt32(HttpContext.Session["RoleID"]); if (SessionControl != 5) { return(RedirectToAction("Index", "Home")); } SetRoleList(); ViewBag.DepartmentList = new SelectList(GetDepartmentList(), "ID", "DEPT_NAME"); try { // if Model does not have any validation error if (model != null) { // Set role List to dropdown list. var userexist = _userRepository.UserFind(model.UNI_ID); if (userexist != null) { return(Json(new ResultJson { Success = false, Message = userexist.UNI_ID + " User Already Registered!" })); } if (string.Compare(model.PASSWORD.Trim().ToUpper(), model.ComparePassword.Trim().ToUpper()) != 0) { return(Json(new ResultJson { Success = false, Message = " Password should match with compare password field!" })); } // Fill as user view model user object from the reguested model and match the value to configure them. user Userdb = new user(); Userdb.UNI_ID = model.UNI_ID.Trim().ToUpper(); Userdb.FIRST_NAME = model.FIRST_NAME; Userdb.LAST_NAME = model.LAST_NAME.ToUpper(); Userdb.EMAIL = model.EMAIL; Userdb.FK_LOCATION_ID = LocationID; Userdb.FK_PRIVILEGE_ID = model.FK_PRIVILEGE_ID; Userdb.IsActive = model.IsActive; Userdb.PHONE = model.PHONE; Userdb.PASSWORD = CustomEncrypt.passwordEncrypt(model.PASSWORD.Trim(), EncryptionKey); Userdb.CREATED_DATE = DateTime.Now; Userdb.UPDATED_DATE = DateTime.Now; Userdb.TITLE = model.TITLE; db.user.Add(Userdb); db.SaveChanges(); return(Json(new ResultJson { Success = true, Message = "User Added Successfully" })); } return(View(model)); } catch (Exception ex) { return(Json(new ResultJson { Success = false, Message = "Error Occured while adding User!" })); } }
private CustomUser GetAutoCreateUser() { CustomUser usr = new CustomUser(); usr.UserName = windowsUserName; //passwords will never get used for a windows auth user, so this is mostly just gibberish, but added so that i don't have to allow nulls for passwords in the database //extra amount of gibberish to potentially avoid a security issue usr.PasswordIterationCount = CustomEncrypt.minimumIterationCount; usr.PasswordSalt = CustomEncrypt.PBKDF2GetRandomSalt(); usr.PasswordHash = CustomEncrypt.PBKDF2HashedPassword(windowsAuthPassword, usr.PasswordSalt, usr.PasswordIterationCount); //*************************************************************** usr.IsUserAutoGenerated = true; usr.DateCreated = System.DateTime.UtcNow; usr.DateLastModified = System.DateTime.UtcNow; //this section is intended on connecting to the domain controller and getting some information about the user to add to our user object //doesn't always work based on the security of the DC. based this attempt on https://stackoverflow.com/questions/20156913/get-active-directory-user-information-with-windows-authentication-in-mvc-4 PrincipalContext ctx = null; try { ctx = new PrincipalContext(ContextType.Domain); UserPrincipalExtended windowsUser = UserPrincipalExtended.FindByIdentity(ctx, User.Identity.Name); if (windowsUser != null) { usr.LastName = windowsUser.Surname; usr.FirstName = windowsUser.GivenName; //windowsUser.Title; //windowsUser.Department; usr.PhoneNumber = windowsUser.VoiceTelephoneNumber; usr.Email = windowsUser.EmailAddress; } } catch (Exception)// ex) { //data was not retrieved successfully from the domain controller. not a good enough reason to cancel the user create, so just move on. } finally { if (ctx != null) { ctx.Dispose(); } } //to avoid empty fields, but that's just a personal choice. if (string.IsNullOrEmpty(usr.FirstName)) { usr.FirstName = windowsUserName; } if (string.IsNullOrEmpty(usr.LastName)) { usr.LastName = windowsUserName; } return(usr); }
public ActionResult RegisterDonor(DonorRegisterViewModel user) { try { if (ModelState.IsValid) { var encryptedPassword = CustomEncrypt.Encrypt(user.Password); if (db.AspNetUsers.FirstOrDefault(o => o.Email == user.Email) != null || db.Donors.FirstOrDefault(o => o.cnp == user.CNP) != null) { TempData["UserAlreadyExists"] = "This donor already exists"; return(View(user)); } var donor = new Donor(); donor.cnp = user.CNP; donor.firstName = user.firstName; donor.lastName = user.lastName; donor.birthDate = user.birthDate; donor.address = user.address; donor.email = user.Email; donor.phoneNumber = user.phoneNumber; if (donor.idBlood != 9) { donor.idBlood = user.idBlood; } db.Donors.Add(donor); var userDb = new AspNetUser(); userDb.Email = user.Email; userDb.Password = encryptedPassword; userDb.idRole = 1; db.AspNetUsers.Add(userDb); db.SaveChanges(); TempData["SuccessRegistration"] = "You registered successfully"; return(RedirectToAction("Login", "Account")); } else { return(View(user)); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue <object>(ve.PropertyName), ve.ErrorMessage); } } throw; } }
public ActionResult Register(RegisterViewModel user) { try { if (ModelState.IsValid) { var encryptedPassword = CustomEncrypt.Encrypt(user.Password); if (db.Patients.Find(user.cardNumber) != null) { if (db.AspNetUsers.Any(o => o.cardNumber == user.cardNumber)) { TempData["UserAlreadyExists"] = "This user already exists"; return(View(user)); } var userDb = new AspNetUser(); userDb.cardNumber = user.cardNumber; userDb.Password = encryptedPassword; userDb.Email = db.Patients.Find(user.cardNumber).email; userDb.idRole = 4; db.AspNetUsers.Add(userDb); db.SaveChanges(); TempData["SuccessRegistration"] = "You registered successfully"; return(RedirectToAction("LoginPatient", "Account")); } else { TempData["Error"] = "You entered a wrong health card number"; return(View(user)); } } else { return(View(user)); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue <object>(ve.PropertyName), ve.ErrorMessage); } } throw; } }
public ActionResult Edit(UserVM User, int?LocationID) { var SessionControl = Convert.ToInt32(HttpContext.Session["RoleID"]); if (SessionControl != 5) { return(RedirectToAction("Index", "Home")); } try { ViewBag.DepartmentList = new SelectList(GetDepartmentList(), "ID", "DEPT_NAME"); SetLocationList(); SetRoleList(); if (User != null) { user dbUser = _userRepository.GetById(User.ID); dbUser.UNI_ID = User.UNI_ID; dbUser.FIRST_NAME = User.FIRST_NAME; dbUser.LAST_NAME = User.LAST_NAME; dbUser.TITLE = User.TITLE; dbUser.PHONE = User.PHONE; dbUser.EMAIL = User.EMAIL; dbUser.FK_LOCATION_ID = LocationID; dbUser.FK_PRIVILEGE_ID = User.FK_PRIVILEGE_ID; if (string.Compare((User.PASSWORD.Trim()), User.ComparePassword.Trim()) != 0) { return(Json(new ResultJson { Success = false, Message = "Password Does not Match!" })); } dbUser.PASSWORD = CustomEncrypt.passwordEncrypt(User.PASSWORD.Trim(), EncryptionKey); dbUser.IsActive = User.IsActive; dbUser.UPDATED_DATE = DateTime.Now; _userRepository.Update(dbUser); _userRepository.Save(); return(Json(new ResultJson { Success = false, Message = "Edit User Succesfull!" })); } else { return(Json(new ResultJson { Success = false, Message = "User Does not find!" })); } } catch (Exception ex) { return(Json(new ResultJson { Success = false, Message = "Error Occured while Editing User!" })); } }
public ActionResult RegisterCentreEmployee(CentreEmployeeRegisterViewModel user) { try { if (ModelState.IsValid) { var encryptedPassword = CustomEncrypt.Encrypt(user.Password); if (db.AspNetUsers.Any(o => o.Email == user.Email)) { TempData["UserAlreadyExists"] = "This employee already exists"; return(View(user)); } var employee = new centerEmployee(); employee.firstName = user.firstName; employee.lastName = user.lastName; employee.email = user.Email; employee.idCenter = user.idCenter; db.centerEmployees.Add(employee); var userDb = new AspNetUser(); userDb.Email = user.Email; userDb.Password = encryptedPassword; userDb.idRole = 2; db.AspNetUsers.Add(userDb); db.SaveChanges(); TempData["SuccessRegistration"] = "You registered successfully"; return(RedirectToAction("Login", "Account")); } else { return(View(user)); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"", ve.PropertyName, eve.Entry.CurrentValues.GetValue <object>(ve.PropertyName), ve.ErrorMessage); } } throw; } }
public ActionResult Login(LoginViewModel user) { if (!ModelState.IsValid) { return(View()); } var emailCheck = db.AspNetUsers.FirstOrDefault(u => u.Email == user.Email && u.idRole != 4); if (emailCheck != null) { var getPassword = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.Password); var materializePassword = getPassword.ToList(); var password = materializePassword[0]; var encryptedPass = CustomEncrypt.Encrypt(user.Password); if (encryptedPass == password) { var getEmail = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.Email); var materializeEmail = getEmail.ToList(); var email = materializeEmail[0]; var idRole = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.idRole); var materializeRole = idRole.ToList(); var role = materializeRole[0]; var roleName = db.AspNetRoles.Find(role).Name.ToString(); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Name, email), new Claim(ClaimTypes.Role, roleName) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var accountManager = ctx.Authentication; accountManager.SignIn(identity); TempData["SuccessRegistration"] = "You signed in into your account as "; return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "The username or password is incorrect"); } } else { ModelState.AddModelError("", "The username or password is incorrect"); } return(View()); }
public bool CrearUsuario(string nombre, string ap, string am, string email, string ci, string userid, string password) { ctlPersonas persona = new ctlPersonas(); try { var personaid = persona.RegistrarPersona(nombre, ap, am, email, ci); using (var db = new DBServices.AccessDBContext()) { var persona_con_acceso = db.Personas_con_Accesos.Create(); persona_con_acceso.PersonaId = personaid; db.Personas_con_Accesos.Add(persona_con_acceso); db.SaveChanges(); if (persona_con_acceso.Id == 0) { throw new Exception("Error en asignacion de acceso..."); } var encryptedpassword = CustomEncrypt.Encrypt(password); var usuario = db.Usuarios.Create(); usuario.UserId = userid; usuario.Password = encryptedpassword; usuario.PersonaId = persona_con_acceso.Id; usuario.PermisoId = 1; db.Usuarios.Add(usuario); db.SaveChanges(); if (usuario.Id != 0) { return(true); } else { return(false); } } } catch (Exception e) { throw e; } finally { } }
public ActionResult Edit(UserVM User, int?id) { try { ViewBag.Role = db.user.Where(x => x.ID == id).Include(x => x.privilege).SingleOrDefault().privilege.ROLE; if (ModelState.IsValid) { var dbUser = db.user.Where(x => x.ID == id).SingleOrDefault(); dbUser.UPDATED_DATE = DateTime.Now; dbUser.PASSWORD = CustomEncrypt.passwordEncrypt(User.PASSWORD, EncryptionKey); dbUser.PHONE = User.PHONE; dbUser.EMAIL = User.EMAIL; db.user.Attach(dbUser); var entry = db.Entry(dbUser); entry.Property(x => x.UPDATED_DATE).IsModified = true; entry.Property(x => x.PASSWORD).IsModified = true; entry.Property(x => x.PHONE).IsModified = true; entry.Property(x => x.EMAIL).IsModified = true; db.SaveChanges(); TempData["info"] = "Profile Edit Succesfully"; return(Json(new ResultJson { Success = false, Message = "Edit User Succesfull!" })); } else { //ModelState.AddModelError() return(Json(new ResultJson { Success = false, Message = "User Does not find!" })); } } catch (Exception ex) { return(Json(new ResultJson { Success = false, Message = "Error Occured while Editing User!" })); } }
public ActionResult Registration(Users model) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.Name = model.Name; user.Country = model.Country; db.Users.Add(user); db.SaveChanges(); } } else { ModelState.AddModelError("", "Missing some field(s) value"); } return(View()); }
public ActionResult Registration(UserViewModel uservm) { if (ModelState.IsValid) { var encryptedPassword = CustomEncrypt.Encrypt(uservm.Password); using (var context = new MvcDbContext()) { var user = context.Users.Create(); user.Email = uservm.Email; user.Password = encryptedPassword; user.Country = uservm.Country; user.Name = uservm.Name; context.Users.Add(user); context.SaveChanges(); } } else { ModelState.AddModelError("", "One or more fields are invalid"); } return(View()); }
public ActionResult Registration(User model) { if (ModelState.IsValid) { using (var db = new OfferEntities1()) { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.Country = model.Country; user.Name = model.Name; db.Users.Add(user); db.SaveChanges(); } } else { ModelState.AddModelError("", "One or more fields have been"); } return(View()); }
public ActionResult Registeration(User user) { if (!ModelState.IsValid) { return(View(user)); } user.PasswordHash = CustomEncrypt.Encrypt(user.PasswordHash); _context.Users.Add(user); _context.SaveChanges(); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.UserName) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var authManager = ctx.Authentication; authManager.SignIn(identity); return(RedirectToAction("Index", "Book")); }
public ActionResult Registration(User model) { if (ModelState.IsValid) { using (var db = new BettingSystemDbContext()) { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Username = model.Username; user.Password = encryptedPassword; db.Users.Add(user); db.SaveChanges(); return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "One or more fields have been missing!"); } return(View()); }
public static string GetPasswordAfterHashing(string passwordToHash, ICustomUser usr) { string providedPasswordAfterHash = passwordToHash; if (!string.IsNullOrEmpty(passwordToHash)) { if (usr != null) { if (usr.PasswordIterationCount > 0 && usr.PasswordSalt != null) { providedPasswordAfterHash = CustomEncrypt.PBKDF2HashedPassword(passwordToHash, usr.PasswordSalt, usr.PasswordIterationCount); } else { throw new InvalidOperationException("no salt or password iteration found"); } } else { throw new InvalidOperationException("usr not declared"); } } return(providedPasswordAfterHash); }
//[Authorize(Roles = RoleNames.ROLE_ADMIN)] public ActionResult Registration(UserFullView ufv_cl) { if (ModelState.IsValid) { using (var db = new MainDbContext()) { //Console.WriteLine(ufv_cl); string encryptedPassword_str = CustomEncrypt.Encrypt(ufv_cl.uli_cl.password); var applicationUser = db.applicationUser.Create(); applicationUser.Password = encryptedPassword_str; applicationUser.UserName = ufv_cl.uli_cl.username; applicationUser.UserFullName = ufv_cl.ubi_cl.userFullName; applicationUser.UserEmployer = ufv_cl.ubi_cl.clientBasicInfo.clientName; applicationUser.UserRole = ufv_cl.ubi_cl.lostAndFoundRoles.roleName; db.applicationUser.Add(applicationUser); db.SaveChanges(); } } return(RedirectToAction("Index", "Admin")); }
private string HashPassword(string password) { return(CustomEncrypt.GetMD5Hash(password)); }
public override void Add(User entity) { entity.Password = CustomEncrypt.Encrypt(entity.Password); base.Add(entity); }
public ActionResult Login(LoginViewModel user) { if (!ModelState.IsValid) { return(View(user)); } var emailCheck = db.AspNetUsers.FirstOrDefault(u => u.Email == user.Email); if (emailCheck != null) { var getPassword = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.Password); var materializePassword = getPassword.ToList(); var password = materializePassword[0]; var encryptedPass = CustomEncrypt.Encrypt(user.Password); if (encryptedPass == password) { string name = ""; if (db.Donors.Any(d => d.email == user.Email) == true) { var getFirstName = db.Donors.Where(u => u.email == user.Email).Select(u => u.firstName); var materName = getFirstName.ToList(); var firstName = materName[0]; var getName1 = db.Donors.Where(u => u.email == user.Email).Select(u => u.lastName); var materName1 = getName1.ToList(); var lastName = materName1[0]; name = "1" + firstName + " " + lastName; } else { if (db.Medics.Any(d => d.email == user.Email) == true) { var getFirstName = db.Medics.Where(u => u.email == user.Email).Select(u => u.firstName); var materName = getFirstName.ToList(); var firstName = materName[0]; var getName1 = db.Medics.Where(u => u.email == user.Email).Select(u => u.lastName); var materName1 = getName1.ToList(); var lastName = materName1[0]; var getCentreId = db.Medics.Where(u => u.email == user.Email).Select(u => u.idHospital); var materId = getCentreId.ToList(); var centreID = materId[0]; name = centreID + firstName + " " + lastName; } else { if (db.centerEmployees.Any(d => d.email == user.Email) == true) { var getFirstName = db.centerEmployees.Where(u => u.email == user.Email).Select(u => u.firstName); var materName = getFirstName.ToList(); var firstName = materName[0]; var getName1 = db.centerEmployees.Where(u => u.email == user.Email).Select(u => u.lastName); var materName1 = getName1.ToList(); var lastName = materName1[0]; var getCentreId = db.centerEmployees.Where(u => u.email == user.Email).Select(u => u.idCenter); var materId = getCentreId.ToList(); var centreID = materId[0]; name = centreID + firstName + " " + lastName; } else //role = admin { name = "1Admin"; } } } var getEmail = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.Email); var materializeEmail = getEmail.ToList(); var email = materializeEmail[0]; var idRole = db.AspNetUsers.Where(u => u.Email == user.Email).Select(u => u.idRole); var materializeRole = idRole.ToList(); var role = materializeRole[0]; var roleName = db.AspNetRoles.Find(role).Name.ToString(); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Role, roleName) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var accountManager = ctx.Authentication; accountManager.SignIn(identity); TempData["SuccessRegistration"] = "You signed in into your account as "; return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "The password is incorrect"); } } else { ModelState.AddModelError("", "The email is incorrect"); } return(View(user)); }
/// <summary> /// Método que trata a exceção gerada. /// </summary> /// <param name="Ex">Exceção não tratada</param> /// <param name="DsEx">DataSet que possui os dados da exceção</param> /// <param name="Nivel">Nível da exceção (caso ocorra exceções derivadas de outras)</param> private void TrataExcecao(Exception Ex, DataSet DsEx, int Nivel) { if (DsEx == null) { DsEx = new DataSet(); } DataTable dt = new DataTable("Erro nível " + Nivel); DataRow r; //Adiciona uma coleção ao DataTable para criar uma arquivo XML. dt.Columns.Add("HelpLink"); dt.Columns.Add("Message"); dt.Columns.Add("Source"); dt.Columns.Add("StackTrace"); dt.Columns.Add("MsgAuxiliar"); dt.Columns.Add("Username"); dt.Columns.Add("Application"); //Tratativa de erros para banco de dados. if (Ex.GetType().ToString() == "Oracle.DataAccess.Client.OracleException" || Ex.GetType().ToString() == "SqlClient.SqlException") { dt.Columns.Add("ErrorCode"); } DsEx.Tables.Add(dt); r = dt.NewRow(); r["HelpLink"] = Ex.HelpLink; r["Message"] = Ex.Message; r["Source"] = Ex.Source; r["StackTrace"] = Ex.StackTrace; r["MsgAuxiliar"] = Ex; r["Username"] = mUsuario; r["Application"] = mApplicatioName; //Caso ser um erro provido em um banco de dados, pego o número (para abrir uma investigação posteriormente). if (Ex.GetType().ToString() == "Oracle.DataAccess.Client.OracleException") { r["ErrorCode"] = Ex.GetType().GetProperty("Number"); mFirstExeType = Ex.GetType().ToString(); mFirstExeCode = Ex.GetType().GetProperty("Number").ToString(); } else if (Ex.GetType().ToString() == "SqlClient.SqlException") { r["ErrorCode"] = ((SqlException)Ex).ErrorCode; mFirstExeType = Ex.GetType().ToString(); mFirstExeCode = ((SqlException)Ex).ErrorCode.ToString(); } dt.Rows.Add(r); //Método recursivo, onde, se o nível (exceptions geradas) for maior que um, salvo no arquivo XML a nova exceção. if (Ex.InnerException != null && Nivel < 5) { TrataExcecao(Ex.InnerException, DsEx, Nivel + 1); } //Gera arquivo físico if (Nivel == 0) { mDirArqLog = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), System.DateTime.Now.ToString("yyyyMMddhhmmss") + ".SkaErro"); DsEx.WriteXml(mDirArqLog); if (mCriptografar) { CustomEncrypt skaEx = new CustomEncrypt(CustomEncrypt.CryptProvider.DES, "DD01039582dd", mDirArqLog); } } }
public ActionResult Registration(RegistrationViewModel model, HttpPostedFileBase file1) { if (ModelState.IsValid) //check if fields empty/valid { try { using (var db = new MainDbContext()) { var emailCheck = db.Users.FirstOrDefault(u => u.Email == model.Email); if (emailCheck == null) //check if account with same email exsist. { var encryptedPassword = CustomEncrypt.Encrypt(model.Password); var user = db.Users.Create(); user.Email = model.Email; user.Password = encryptedPassword; user.FirstName = model.FirstName; user.LastName = model.LastName; user.Country = RegionInfo.CurrentRegion.DisplayName; //save user uploaded picture to the database as binary. byte[] imgByte = null; if (file1 != null && file1.ContentLength > 0) { MemoryStream target = new MemoryStream(); file1.InputStream.CopyTo(target); imgByte = target.ToArray(); user.DisplayPicture = imgByte; } else { user.DisplayPicture = imgByte; //set null } db.Users.Add(user); //add provided data to sample database db.SaveChanges(); TempData["msg-type"] = "alert-success"; TempData["msg-head"] = "Success"; TempData["msg-des"] = "Account created successfully!! Login from here."; return(RedirectToAction("Login", "Auth")); } TempData["msg-type"] = "alert-warning"; TempData["msg-head"] = "Warning"; TempData["msg-des"] = "Account already exist for this email!!"; return(View()); } } catch (ProviderIncompatibleException) { TempData["msg-type"] = "alert-danger"; TempData["msg-head"] = "Oh Snap!!"; TempData["msg-des"] = "Unable to create account!! Could not establish connection with server!!"; return(View(model)); } } TempData["msg-type"] = "alert-warning"; TempData["msg-head"] = "Warning"; TempData["msg-des"] = "Account creation was unsuccessful. Please correct the errors and try again!!"; return(View()); }
protected override void Seed(library_prototype.DAL.LibraryDbContext context) { var crypto = new SimpleCrypto.PBKDF2(); var encrypPass = crypto.Compute("rodnerraymundo"); string pin = RandomPassword.Generate(6, PasswordGroup.Lowercase, PasswordGroup.Lowercase, PasswordGroup.Numeric); var cryptoPin = new SimpleCrypto.PBKDF2(); var encrypPin = crypto.Compute(pin); var grades = new List <library_prototype.DAL.LibraryDbContext.GradesModel> { new library_prototype.DAL.LibraryDbContext.GradesModel { Grade = "Administrator", CreatedAt = DateTime.UtcNow, Sections = new List <library_prototype.DAL.LibraryDbContext.SectionsModel> { context.Sections.SingleOrDefault(s => s.Section == "Developer") } } }; grades.ForEach(g => context.Grades.AddOrUpdate(g)); var sections = new List <library_prototype.DAL.LibraryDbContext.SectionsModel> { new library_prototype.DAL.LibraryDbContext.SectionsModel { Section = "Developer", CreatedAt = DateTime.UtcNow, } }; sections.ForEach(s => context.Sections.AddOrUpdate(s)); var addresses = new List <library_prototype.DAL.LibraryDbContext.StudentAddressModel> { new DAL.LibraryDbContext.StudentAddressModel { Address1 = "Lumang Dito", Address2 = "Banda Rito", City = "Pineapple City", Country = "Philippines", CreatedAt = DateTime.UtcNow, ZipCode = 1234 }, new DAL.LibraryDbContext.StudentAddressModel { Address1 = "Matuwid na Daan", Address2 = "Pork Doon", City = "Apple City", Country = "Philippines", CreatedAt = DateTime.UtcNow, ZipCode = 5678 }, new DAL.LibraryDbContext.StudentAddressModel { Address1 = "Dating Dito", Address2 = "Banda Doon", City = "Pineapple City", Country = "Philippines", CreatedAt = DateTime.UtcNow, ZipCode = 9012 } }; addresses.ForEach(a => context.StudentAddresses.AddOrUpdate(a)); context.SaveChanges(); var accounts = new List <library_prototype.DAL.LibraryDbContext.UserModel> { new library_prototype.DAL.LibraryDbContext.UserModel { Email = "*****@*****.**", Password = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt, Role = "administrator", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo", CreatedAt = DateTime.UtcNow, Status = true, Student = new DAL.LibraryDbContext.StudentModel { FirstName = "Rodner", MiddleInitial = "A", LastName = "Raymundo", Status = true, Birthday = DateTime.UtcNow.AddYears(-20), ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male", StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 9012), Section = context.Sections.SingleOrDefault(s => s.Section == "Developer") } }, new library_prototype.DAL.LibraryDbContext.UserModel { Email = "*****@*****.**", Password = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt, Role = "staff", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo", CreatedAt = DateTime.UtcNow, Status = true, Student = new DAL.LibraryDbContext.StudentModel { FirstName = "Kevin", MiddleInitial = "G", LastName = "Tiu", Status = true, Birthday = DateTime.UtcNow.AddYears(-20), ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male", StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 5678), Section = context.Sections.SingleOrDefault(s => s.Section == "Developer") } }, new library_prototype.DAL.LibraryDbContext.UserModel { Email = "*****@*****.**", Password = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt, Role = "student", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo", CreatedAt = DateTime.UtcNow, Status = true, Student = new DAL.LibraryDbContext.StudentModel { FirstName = "Jake", MiddleInitial = "S", LastName = "Arroyo", Status = true, Birthday = DateTime.UtcNow.AddYears(-15), ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male", StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 1234), Section = context.Sections.SingleOrDefault(s => s.Section == "Developer") } }, }; accounts.ForEach(a => context.Users.AddOrUpdate(a)); try { context.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } var publishers = new List <DAL.LibraryDbContext.PublisherModel> { new DAL.LibraryDbContext.PublisherModel { PublisherName = "Kewl Publisher", CreatedAt = DateTime.UtcNow, } }; publishers.ForEach(p => context.Publishers.AddOrUpdate(p)); var subjects = SubjectSeeder.Subject(); subjects.ForEach(s => context.Subjects.AddOrUpdate(s)); context.SaveChanges(); var books = new List <library_prototype.DAL.LibraryDbContext.BookModel> { new library_prototype.DAL.LibraryDbContext.BookModel { Title = "Discrete Mathematics for Kids", ISBN = "978-971-95546-0-8", Copyright = new DateTime(2012, 1, 1), NoOfPages = 215, Price = 165.00, Quantity = 2, Synopsis = "This book is for students who failed Discrete Mathematics", Borrow = true, CreatedAt = DateTime.UtcNow, Volume = "1", Subject = context.Subjects.SingleOrDefault(s => s.CallNo == 001), Publisher = context.Publishers.SingleOrDefault(p => p.PublisherName == "Kewl Publisher") } }; books.ForEach(b => context.Books.AddOrUpdate(b)); var authors = new List <library_prototype.DAL.LibraryDbContext.AuthorModel> { new library_prototype.DAL.LibraryDbContext.AuthorModel { LastName = "Gonzales", FirstName = "George", MiddleInitial = "A", } }; authors.ForEach(a => context.Authors.AddOrUpdate(a)); var booksauthors = new List <library_prototype.DAL.LibraryDbContext.BookAuthorModel> { new library_prototype.DAL.LibraryDbContext.BookAuthorModel { Book = context.Books.SingleOrDefault(b => b.Title == "Discrete Mathematics for Kids"), Author = context.Authors.SingleOrDefault(a => a.LastName == "Gonzales"), } }; booksauthors.ForEach(b => context.BooksAuthors.AddOrUpdate(b)); context.SaveChanges(); var emailCredential = new List <DAL.LibraryDbContext.EmailCredentialModel> { new DAL.LibraryDbContext.EmailCredentialModel { Host = "smtp.sendgrid.net", Username = "******", Password = CustomEncrypt.Encrypt("bg5PSAAPof9L2TW"), CreatedAt = DateTime.UtcNow, Deleted = false, EmailMessages = new List <DAL.LibraryDbContext.EmailMessageModel> { new DAL.LibraryDbContext.EmailMessageModel { Type = "notification", From = "*****@*****.**", Subject = "Book Deadline", Body = "This is a reminder that your borrowed book's deadline is coming near. We urge you to return the book on or before it's deadline. Thank you", CreatedAt = DateTime.UtcNow, Deleted = false, }, new DAL.LibraryDbContext.EmailMessageModel { Type = "accountpincode", From = "*****@*****.**", Subject = "Account Activation", Body = "You have received because you are registered at Santo Tomas de Villanueva Parochial School Web and Android Online Public Access Catalog System. Otherwise please disregard this email.", CreatedAt = DateTime.UtcNow, Deleted = false, } } } }; emailCredential.ForEach(e => context.EmailCredentials.AddOrUpdate(e)); context.SaveChanges(); /*var information = new List<library_prototype.DAL.LibraryDbContext.StudentModel> * { * new DAL.LibraryDbContext.StudentModel * { * FirstName = "Rodner", MiddleInitial = "Y", LastName = "Raymundo", Status = true, * ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male", * } * }; * information.ForEach(i => context.Students.AddOrUpdate(i)); */ /* * var sections = new List<library_prototype.DAL.LibraryDbContext.SectionsModel> * { * new DAL.LibraryDbContext.SectionsModel * { * Section = "Administrator", CreatedAt = DateTime.UtcNow, * }, * * new DAL.LibraryDbContext.SectionsModel * { * Section = "Co-Administrator", CreatedAt = DateTime.UtcNow, * } * }; * var nonStudentGroup = context.Grades.FirstOrDefault(g => g.Grade == "Non-student"); * sections.ForEach(s => nonStudentGroup.Sections.Add(s)); * context.SaveChanges(); */ base.Seed(context); }
public ActionResult EditUser(UserInfo ui) { SetRolesForViewBag(); SetTypeOfActionWithRequestForm("Edit"); if (!ModelState.IsValid) //Checks if input fields have the correct format { return(View(ui)); //Returns the view with the input values so that the user doesn't have to retype again } try { if (CheckIfSuchUserAlreadyExistsInDatabase(ui.userId, true) == true) { ModelState.AddModelError("userId", "Username must be unique"); return(View(ui)); } else { string connectionStringCommon = CommonManager.ReturnNeededConnectionStringForCommonDatabase(); string decryptedPassword = CustomEncrypt.Encrypt(ui.userPwd); string sqlToUpdateInfoAboutUser = @"UPDATE tblUser SET userId=@userId, userPwd=@userPwd WHERE userUniqueDatabaseId = @userUniqueDatabaseId"; using (SqlConnection conn = new SqlConnection(connectionStringCommon)) { conn.Open(); SqlCommand cmdToUpdateInfoAboutUser = new SqlCommand(sqlToUpdateInfoAboutUser, conn); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userId", ui.userId); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userPwd", decryptedPassword); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userUniqueDatabaseId", ui.uniqueUserId); cmdToUpdateInfoAboutUser.ExecuteNonQuery(); } string connectionStringHotel = CommonManager.ReturnNeededConnectionStringForHotel(); string sqlToUpdateMainInfoAboutUser = @"UPDATE tblUserInformation SET userType=@userType, userFullName=@userFullName, userEmail=@userEmail, userId=@userId, userPhoneNumber=@userPhoneNumber WHERE userUniqueDatabaseId = @userUniqueDatabaseId"; using (SqlConnection conn = new SqlConnection(connectionStringHotel)) { conn.Open(); SqlCommand cmdToUpdateInfoAboutUser = new SqlCommand(sqlToUpdateMainInfoAboutUser, conn); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userType", ui.userType); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userFullName", ui.userFullName); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userUniqueDatabaseId", ui.uniqueUserId); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userEmail", ui.userEmail); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userId", ui.userId); cmdToUpdateInfoAboutUser.Parameters.AddWithValue("@userPhoneNumber", ui.userPhoneNumber); cmdToUpdateInfoAboutUser.ExecuteNonQuery(); } return(RedirectToAction("Index")); } } catch (Exception ex) { //Console.WriteLine(ex); return(HttpNotFound("Something went wrong. Please, contact the administration")); } }
public ActionResult CreateUser([Bind(Exclude = "uniqueUserId")] UserInfo ui) { SetRolesForViewBag(); SetTypeOfActionWithRequestForm("Create"); if (!ModelState.IsValid) //Checks if input fields have the correct format { return(View(ui)); //Returns the view with the input values so that the user doesn't have to retype again } else { try { string decryptedPassword = CustomEncrypt.Encrypt(ui.userPwd); if (CheckIfSuchUserAlreadyExistsInDatabase(ui.userId, false) == true) { ModelState.AddModelError("userId", "Username must be unique"); return(View(ui)); } else { string uniqueEightDigitNumber = GenerateUniqueValues.ReturnUniqueEightDigitNumber(); string connectionStringCommon = CommonManager.ReturnNeededConnectionStringForCommonDatabase(); string sqlToCreateUser = @"INSERT INTO tblUser (userId, userPwd, userEmployer, userUniqueDatabaseId, ifRemoved) VALUES (@userId, @userPwd, @userEmployer, @userUniqueDatabaseId, @ifRemoved)"; using (SqlConnection conn = new SqlConnection(connectionStringCommon)) { conn.Open(); SqlCommand cmdToCreateUser = new SqlCommand(sqlToCreateUser, conn); cmdToCreateUser.Parameters.AddWithValue("@userId", ui.userId); cmdToCreateUser.Parameters.AddWithValue("@userPwd", decryptedPassword); cmdToCreateUser.Parameters.AddWithValue("@userEmployer", GetCurrentClaimValues.GetCurrentUserEmployer()); cmdToCreateUser.Parameters.AddWithValue("@userUniqueDatabaseId", uniqueEightDigitNumber); cmdToCreateUser.Parameters.AddWithValue("@ifRemoved", 0); cmdToCreateUser.ExecuteNonQuery(); } string connectionStringHotel = CommonManager.ReturnNeededConnectionStringForHotel(); string sqlToCreateInfoAboutUser = @"INSERT INTO tblUserInformation (userFullName, userType, userId, userUniqueDatabaseId, userEmail, userPhoneNumber, ifRemoved) VALUES (@userFullName, @userType, @userId, @userUniqueDatabaseId, @userEmail, @userPhoneNumber, @ifRemoved)"; using (SqlConnection conn = new SqlConnection(connectionStringHotel)) { conn.Open(); SqlCommand cmdToCreateMainUser = new SqlCommand(sqlToCreateInfoAboutUser, conn); cmdToCreateMainUser.Parameters.AddWithValue("@userId", ui.userId); cmdToCreateMainUser.Parameters.AddWithValue("@userFullName", ui.userFullName); cmdToCreateMainUser.Parameters.AddWithValue("@userType", ui.userType); cmdToCreateMainUser.Parameters.AddWithValue("@userUniqueDatabaseId", uniqueEightDigitNumber); cmdToCreateMainUser.Parameters.AddWithValue("@userEmail", ui.userEmail); cmdToCreateMainUser.Parameters.AddWithValue("@userPhoneNumber", ui.userPhoneNumber); cmdToCreateMainUser.Parameters.AddWithValue("@ifRemoved", 0); cmdToCreateMainUser.ExecuteNonQuery(); if (ui.userType == "Driver") { string sqlDriverAvailability = @"INSERT INTO tblDriverAvailability VALUES (@driverUniqueId, @driverAvailability)"; SqlCommand cmdToCreateDriverAvailability = new SqlCommand(sqlDriverAvailability, conn); cmdToCreateDriverAvailability.Parameters.AddWithValue("@driverUniqueId", uniqueEightDigitNumber); cmdToCreateDriverAvailability.Parameters.AddWithValue("@driverAvailability", true); cmdToCreateDriverAvailability.ExecuteNonQuery(); } } return(RedirectToAction("Index")); } } catch (Exception ex) { //Console.WriteLine(ex); return(HttpNotFound("Something went wrong. Please, contact the administration")); } } }