public IActionResult Register(UsersWrapper user) { Users SubUser = user.NewUser; CryptoEngine Encrypter = new CryptoEngine(); if (ModelState.IsValid) { bool ExUser = dbContext.users.Any(t => t.Email == SubUser.Email); if (ExUser == true) { ModelState.AddModelError("NewUser.Email", "email already exists"); return(View("Index")); } PasswordHasher <Users> Hasher = new PasswordHasher <Users>(); SubUser.Password = Hasher.HashPassword(SubUser, SubUser.Password); SubUser.Email = Encrypter.Encrypt(SubUser.Email); SubUser.UserName = Encrypter.Encrypt(SubUser.UserName); dbContext.users.Add(SubUser); dbContext.SaveChanges(); Users CurUser = dbContext.users.Last(); HttpContext.Session.SetInt32("userid", CurUser.UserId); return(RedirectToAction("Success")); } else { return(View("Index")); } }
public ActionResult Cuenta(CuentaModificadaViewModel model) { Cuenta oCuenta = (Cuenta)Session["Usuario"]; model.nombre = oCuenta.nombre; if (!ModelState.IsValid) { return(View(model)); } if (oCuenta.contrasena != CryptoEngine.Encrypt(model.contrasena)) { ModelState.AddModelError("contrasena", "Contraseña incorrecta"); return(View(model)); } using (var db = new SaludOcupacionalEntities()) { string contrasenaNueva = CryptoEngine.Encrypt(model.contrasenaNueva); oCuenta.contrasena = contrasenaNueva; db.Entry(oCuenta).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); TempData["Success"] = "Contraseña cambiada correctamente"; } return(View(model)); }
public async Task <RegisterMasterStoreResponseEntity> RegisterMasterStore(RegisterMasterStoreRequestEntity reqEntity) { if (!Connectivity.IsInternetAvailable) { return(new RegisterMasterStoreResponseEntity() { StatusCode = (int)GenericStatusValue.NoInternetConnection }); } var reqContract = Mapper.Map <RegisterMasterStoreRequestContract>(reqEntity); var respContract = await _windowsWebService.RegisterMasterStore(reqContract); var respEntity = Mapper.Map <RegisterMasterStoreResponseEntity>(respContract); if (respEntity.StatusCode == (int)GenericStatusValue.Success) { respEntity.TimeZone = reqEntity.SelectedTimeZone; string json = JsonConvert.SerializeObject(respEntity); json = CryptoEngine.Encrypt(json, Config.SymmetricKey); using (var outputFile = new StreamWriter(Config.FilePath + "master-store.json", false, Encoding.UTF8)) { outputFile.WriteLine(json); } File.SetAttributes(Config.FilePath + "master-store.json", FileAttributes.Hidden); } return(respEntity); }
public static bool SaveUserData(string data) { var encryptData = CryptoEngine.Encrypt(data, Keys.SymmetricKey); try { // Does the config folder not exist? if (!Directory.Exists(AppPath)) { Directory.CreateDirectory(AppPath); // Create the Config File Exmaple folder1 } using (var outputFile = new StreamWriter($"{FilePath}{ValidatedUserJson}", false, Encoding.UTF8)) outputFile.WriteLine(encryptData); if (FilePath != null) { File.SetAttributes($"{FilePath}{ValidatedUserJson}", FileAttributes.Hidden); } return(true); } catch (IOException) { return(false); } }
public void Add_XP(int amount) { xpPoint += amount; Debug.Log(xpPoint); string xpStringDecrypted = xpPoint.ToString(); string xpStringEncrypted = CryptoEngine.Encrypt(xpStringDecrypted, XP_ENCRYPTION_KEY); PlayerPrefs.SetString(XP_COIN_SAVE, xpStringEncrypted); // PlayerPrefs.SetInt("XP_POINT", xpPoint); //OnXPUpdateAction?.Invoke(); if (PlayFabClientAPI.IsClientLoggedIn()) { if (Application.internetReachability != NetworkReachability.NotReachable) { PlayfabController.Instance.Add_XP(amount); //XP_Equalization() } else { //Crashlytics.Log("XP_System.cs|Add_XP(int amount) : Saving xp offline which are failed to save in server"); OfflineXPSave(amount); } } else { //Crashlytics.Log("XP_System.cs|Add_XP(int amount) : Saving xp offline which are failed to save in server"); OfflineXPSave(amount); } }
public ActionResult <Response> Put([FromBody] User user) { try { if (HttpContext.Session.GetString("is_login").ToLower().Equals("true")) { var oldUser = appDbContext.Users.SingleOrDefault(p => p.Id == int.Parse(HttpContext.Session.GetString("userid"))); if (oldUser != null) { oldUser.Password = CryptoEngine.Encrypt(user.Password, "sblw-3hn8-sqoy19"); appDbContext.SaveChanges(); return(new Response(oldUser)); } else { return(new Response(null, 404, "No User Found")); } } else { return(new Response(null, 404, "Authentication Failure")); } } catch (Exception ex) { logger.LogError(ex, user.ToString()); return(new Response(null, 404, ex.Message)); } }
private void btnAddUser_Click(object sender, EventArgs e) { try { Usuario = new Usuarios(); Usuario.Nombre = txtNombre.Text; Usuario.Apellido = txtApellido1.Text; Usuario.Telefono = txtTelefono.Text; Usuario.Correo = txtEmail.Text; Usuario.Direccion = txtDireccion.Text; Usuario.RolUsuario = (int)cmbBoxRol.SelectedValue; // Usuario.RolUsuario = (RolUsuarios)cmbBoxRol.SelectedItem; Usuario.Contrasena = cryptoEngine.Encrypt(txtContrasena.Text); Usuario.FechaCreacion = DateTime.Now; usuariosDAL.Add(Usuario); MessageBox.Show("Usuario agregado"); frmUsuarios frmUsuarios = new frmUsuarios(); this.Hide(); frmUsuarios.Show(); } catch (Exception ex) { MessageBox.Show("Error " + ex.Message); } }
private void btnModifyUser_Click(object sender, EventArgs e) { try { Usuario.Nombre = txtNombre.Text; Usuario.Apellido = txtApellido1.Text; Usuario.Telefono = txtTelefono.Text; Usuario.Correo = txtEmail.Text; Usuario.Direccion = txtDireccion.Text; Usuario.RolUsuario = (int)cmbBoxRol.SelectedValue; // Usuario.RolUsuario = (RolUsuarios)cmbBoxRol.SelectedItem; Usuario.Contrasena = crypto.Encrypt(txtContrasena.Text); usuariosDAL.Update(Usuario); MessageBox.Show("Usuario actualizado"); frmUsuarios frmUsuarios = new frmUsuarios(); this.Hide(); frmUsuarios.Show(); } catch (Exception ex) { MessageBox.Show("Error " + ex.Message); } }
public ActionResult SignUpSubmit(USER_MASTER objUSER_MASTER) { string Msg = ""; try { if (objUSER_MASTER.PASSWORD != objUSER_MASTER.CONFIRM_PASSWORD) { Msg = "Password is not matched"; } else { string pass = ""; pass = CryptoEngine.Encrypt(objUSER_MASTER.PASSWORD, "sblw-3hn8-sqoy19"); objUSER_MASTER.PASSWORD = pass; Msg = objUSER_MASTER.SaveData(); } } catch (Exception ex) { ViewBag.Message = ex.Message; } ViewBag.Message = Msg; return(View("~/Views/LogIn/SignUp.cshtml", objUSER_MASTER)); }
public ActionResult AddAdminUser(CuentaViewModel model) { if (!ModelState.IsValid) { return(View(model)); } using (var db = new SaludOcupacionalEntities()) { // Revisa si el nombre de usuario ya existe var usernameExists = db.Cuenta.Any(x => x.nombre == model.nombre); if (usernameExists) { ModelState.AddModelError("nombre", "Este nombre de usuario ya existe"); return(View(model)); } Cuenta oCuenta = new Cuenta(); oCuenta.nombre = model.nombre; oCuenta.contrasena = CryptoEngine.Encrypt(model.contrasena); oCuenta.rol = 0; // Rol 0 significa "administrador" db.Cuenta.Add(oCuenta); db.SaveChanges(); } return(Redirect(Url.Content("~/AdminCuenta"))); }
private static string GetEncryptedPassword() { string cryptKey = ConfigSettings.CryptKey; string password = CryptoEngine.Encrypt(MagicStrings.PASSWORD, true, cryptKey); return(password); }
/// <summary> /// Handles the Click event of the btnLogin control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param> private void btnLogin_Click(object sender, RoutedEventArgs e) { if (!string.IsNullOrEmpty(EdUserName.Text)) { Request.Password = CryptoEngine.Encrypt(EdPwd.Password); Request.UserName = EdUserName.Text; DialogResult = true; } }
public void Login() { Request.Password = CryptoEngine.Encrypt(Password); Feedback = String.Format("Authenticating user '{0}'", Request.UserName); AuthenticationPortal .Authentication .AuthenticateByUserNameAndPasswordAsync(Request.UserName, Request.Password, OnNativeAuthenticationCompleted); }
/// <summary> /// Get authorized non-admin user details for login /// </summary> /// <param name="username">email Id</param> /// <param name="password">password</param> /// <returns>return full user details</returns> public User Login(string username, string password) { string decryptedPassword = CryptoEngine.Encrypt(password, "sblw-3hn8-sqoy19"); var user = dbcontext.Users.FirstOrDefault(a => a.Email.ToLower() == username.ToLower() && a.Password == decryptedPassword && a.IsAdmin == true); return(user); }
private FormUrlEncodedContent MakeFormContent() { var formcontent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>(Resources.Email, Email), new KeyValuePair <string, string>(Resources.Password, CryptoEngine.Encrypt(Password, Resources.CryptoKey)) }); return(formcontent); }
/// <summary> /// Register new user /// </summary> /// <param name="user">all the data of new user</param> /// <returns>newly registered user's Id</returns> public long Register(User user) { string encryptedPassword = CryptoEngine.Encrypt(user.Password, "sblw-3hn8-sqoy19"); user.Password = encryptedPassword; dbcontext.Users.Add(user); dbcontext.SaveChanges(); return(user.ID); }
private FormUrlEncodedContent MakeFormContent() { var formcontent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>(Resources.Email, AppSettings.GetValueOrDefault(Resources.ForgotPasswordMail, Resources.DefaultStringValue)), new KeyValuePair <string, string>(Resources.NewPassword, CryptoEngine.Encrypt(NewPassword, Resources.CryptoKey)) }); return(formcontent); }
private Users CreateUser() { Users User = new Users(); User.FirstName = AppSettings.GetValueOrDefault(Resources.FirstName, Resources.DefaultStringValue); User.LastName = AppSettings.GetValueOrDefault(Resources.LastName, Resources.DefaultStringValue); User.Phone = CryptoEngine.Encrypt(AppSettings.GetValueOrDefault(Resources.UserPhone, Resources.DefaultStringValue), Resources.CryptoKey); User.UserPassword = CryptoEngine.Encrypt(AppSettings.GetValueOrDefault(Resources.UserPassword, Resources.DefaultStringValue), Resources.CryptoKey); User.Email = AppSettings.GetValueOrDefault(Resources.UserName, Resources.DefaultStringValue); return(User); }
public IActionResult Login(UsersWrapper user) { LoginUsers SubUser = user.LoginUser; CryptoEngine Encrypter = new CryptoEngine(); if (ModelState.IsValid) { SubUser.Email = Encrypter.Encrypt(SubUser.Email); Users userInDb = dbContext.users.FirstOrDefault(u => u.Email == SubUser.Email); if (userInDb == null) { ModelState.AddModelError("LoginUser.Email", "Invalid Email"); return(View("Index")); } var hasher = new PasswordHasher <LoginUsers>(); var result = hasher.VerifyHashedPassword(SubUser, userInDb.Password, SubUser.Password); if (result == 0) { ModelState.AddModelError("LoginUser.Password", "Password is wrong"); return(View("Index")); } HttpContext.Session.SetInt32("userid", userInDb.UserId); return(RedirectToAction("Success")); // SubUser.Email=Users.Encrypt(SubUser.Email); // List<Users> AllUsers=dbContext.users.ToList(); // foreach(Users item in AllUsers){ // item.Email=Encrypter.Decrypt(item.Email); // if(item.Email==user.LoginUser.Email){ // Users userInDb = dbContext.users.FirstOrDefault(u => u.UserId == item.UserId); // HttpContext.Session.SetInt32("userid",userInDb.UserId); // var hasher = new PasswordHasher<LoginUsers>(); // var result = hasher.VerifyHashedPassword(SubUser, userInDb.Password, SubUser.Password); // if(result == 0){ // ModelState.AddModelError("LoginUser.Password", "Password is wrong"); // return View("Index"); // } // return RedirectToAction("Success"); // } // } // ModelState.AddModelError("LoginUser.Email", "Invalid Email"); // return View("Index"); // return // if(userInDb == null) // { // } } else { return(View("Index")); } }
public async Task <IActionResult> Process(IEnumerable <IFormFile> files) { long size = files.Sum(f => f.Length); List <string> filePaths = new List <string>(); List <byte[]> imgs_bytes = new List <byte[]>(); foreach (var file in files) { if (file.Length > 0 && file.ContentType.Contains("image")) { string datetime = DateTime.Now.ToString("yyyy_MM_dd__HH_mm_ss"); string filetype = "." + file.ContentType.Split("/")[1]; string filename = datetime + filetype; string filePath = $"{_imgUploadDir}/{filename}"; filePaths.Add(filePath); string type = file.GetType().ToString(); using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { await file.CopyToAsync(stream); } } } // process uploaded files CryptoEngine Encryptor = new CryptoEngine(); foreach (string path in filePaths) { string encryptedPath = Encryptor.Encrypt(path); Photos img = new Photos { PhotoPath = encryptedPath }; db.Add(img); } db.SaveChanges(); // Don't rely on or trust the FileName property without validation. string[] firstfilepath = filePaths[0].Split("\\"); int lastsegment = firstfilepath.Length - 1; string firstfilename = firstfilepath[lastsegment]; Recognizer r = new Recognizer(); List <ItemToView> ResultList = r.recognizeIt($"./wwwroot/uploads/{firstfilename}"); return(View("Result", ResultList)); }
public IActionResult AddPhoto(Photos NewPhoto) { // int? y=HttpContext.Session.GetInt32("userid"); // if (y==null){ // return RedirectToAction("Index"); // } // bool Exists=dbContext.users.Any(e=>e.UserId==(int)y); // if(Exists==false){ // return RedirectToAction("Index"); // } if (ModelState.IsValid) { CryptoEngine Encrypter = new CryptoEngine(); NewPhoto.Desc = Encrypter.Encrypt(NewPhoto.Desc); NewPhoto.PhotoPath = Encrypter.Encrypt(NewPhoto.PhotoPath); // NewPhoto.CreatorId=Encrypter.Encrypt((string)NewPhoto.CreatorId); dbContext.photos.Add(NewPhoto); dbContext.SaveChanges(); return(RedirectToAction("Success")); } else { // ViewBag.UserId=(int)y; ViewBag.UserId = 5; List <Photos> Allphoto = dbContext.photos.ToList(); foreach (var photo in Allphoto) { CryptoEngine Encrypter = new CryptoEngine(); photo.Desc = Encrypter.Decrypt(photo.Desc); photo.PhotoPath = Encrypter.Decrypt(photo.PhotoPath); } ViewBag.AllPhotos = Allphoto; return(View("Success")); } }
public void Submit() { Registering = true; UserInfo.Password = CryptoEngine.Encrypt(Password); UserInfo.ConfirmedPassword = CryptoEngine.Encrypt(ConfirmedPassword); UserInfo.UserName = UserInfo.Email; if (UserInfo.HasErrors) { return; } Feedback = String.Format("Registering User: {0} {1}.", UserInfo.FirstName, UserInfo.LastName); AuthenticationPortal .Authentication .RegisterNewUserAsync(UserInfo, RegisterNewUserCompleted); }
public ActionResult Index(LoginModel aLoginModel) { var encryptPassword = CryptoEngine.Encrypt(aLoginModel.Password); var success = db.Registers.FirstOrDefault(a => a.Password.Equals(encryptPassword)); if (success != null) { TempData.Clear(); TempData["Password"] = encryptPassword; return(RedirectToAction("Index", "Success")); } ViewBag.Message = "Doesn't Match your Password!"; return(View()); }
public ActionResult Index(LoginViewModel model) { if (!ModelState.IsValid) { return(View(model)); } using (var db = new SaludOcupacionalEntities()) { model.contrasena = CryptoEngine.Encrypt(model.contrasena); var cuenta = from d in db.Cuenta where d.nombre == model.username select d; if (cuenta.Count() == 0) { ModelState.AddModelError("username", "Usuario inválido"); return(View(model)); } Cuenta oCuenta = cuenta.First(); if (oCuenta.contrasena != model.contrasena) { ModelState.AddModelError("contrasena", "Contraseña incorrecta"); return(View(model)); } Session["Usuario"] = oCuenta; if (oCuenta.rol == 0) { return(Redirect(Url.Content("~/AdminComision"))); } else { var comision = (from d in db.Comision join c in db.Cuenta on d.idCuenta equals oCuenta.idCuenta select d.idComision); int idComision = comision.First(); Session["idComision"] = idComision; return(Redirect(Url.Content("~/ComisionUser/InformacionPrincipal/" + idComision))); } } }
private void btnEncrypt_Click(object sender, EventArgs e) { try { if (txtEnCrypt.Text != string.Empty) { //Here key is of 128 bit //Key should be either of 128 bit or of 192 bit string paddedText = txtEnCrypt.Text + _machineName; txtCypher.Text = CryptoEngine.Encrypt(txtEnCrypt.Text, _cypherText); } } catch (Exception ex) { } }
public ActionResult <Response> Post([FromBody] User user) { try { user.Password = CryptoEngine.Encrypt(user.Password, "sblw-3hn8-sqoy19"); appDbContext.Users.Add(user); appDbContext.SaveChangesAsync(); user.Password = CryptoEngine.Decrypt(user.Password, "sblw-3hn8-sqoy19"); return(new Response(user, 200, "User Inserted Successfully")); } catch (Exception ex) { logger.LogError(ex, user.ToString()); return(new Response(null, 404, ex.Message)); } }
/// <summary> /// Update user details /// </summary> /// <param name="user">updated user object from frontend</param> /// <returns>updated user Id</returns> public long UpdateUser(User user) { var userdata = dbcontext.Users.FirstOrDefault(a => a.ID == user.ID); userdata.FirstName = user.FirstName; userdata.LastName = user.LastName; userdata.Email = user.Email; userdata.Mobile = user.Mobile; userdata.Password = CryptoEngine.Encrypt(user.Password, "sblw-3hn8-sqoy19"); userdata.IsActive = user.IsActive; userdata.IsAdmin = user.IsAdmin; dbcontext.SaveChanges(); return(userdata.ID); }
public void XP_Equalization() { if (PlayFabClientAPI.IsClientLoggedIn()) { try { Dictionary <string, int> vc = new Dictionary <string, int>(); PlayFabClientAPI.GetUserInventory( new GetUserInventoryRequest { }, GetResult => { vc = GetResult.VirtualCurrency; //Debug.Log("GOLD :" + vc["GD"] + " | XP:" + vc["XP"]); //Debug.Log("XP Point on Game: " + xpPoint); if (CoinSystem.instance != null) { CoinSystem.instance.SetBalance(vc["GD"]); } if (vc["XP"] >= xpPoint) { xpPoint = vc["XP"]; string xpStringDecrypted = xpPoint.ToString(); string xpStringEncrypted = CryptoEngine.Encrypt(xpStringDecrypted, XP_ENCRYPTION_KEY); PlayerPrefs.SetString(XP_COIN_SAVE, xpStringEncrypted); // PlayerPrefs.SetInt("XP_POINT", xpPoint); } else { PlayfabController.Instance.Add_XP(xpPoint - vc["XP"]); } OnXPUpdateAction?.Invoke(); }, (op) => { Debug.LogError("unable to gets xp data from server !!!" + op.ErrorMessage); } ); } catch (Exception e) { // Crashlytics.Log("XP_System.Add_XP() : " + e); // Crashlytics.LogException(e); Debug.LogError("unable to gets xp data from server !!!" + e.Message); } } OnXPUpdateAction?.Invoke(); }
public ActionResult Login(LoginModels _login) { if (ModelState.IsValid) //validating the user inputs { //bool isExist = false; string username = _login.UserName.Trim(); string password = CryptoEngine.Encrypt(_login.Password.Trim()); List <LoginModels> LogList = kpiHRD.ListMenu(username, password); if (LogList.Count == 0) { ViewBag.ErrorMsg = "Please enter the valid credentials!..."; return(View()); } //userroleid = Convert.ToInt32(LogList[0].UserRoleId); else { FormsAuthentication.SetAuthCookie(LogList[0].UserName, false); // set the formauthentication cookie Session["LoginCredentials"] = LogList[0]; // Bind the _logincredentials details to "LoginCredentials" session //Session["MenuMaster"] = LogListMenu; //Bind the _menus list to MenuMaster session Session["UserName"] = LogList[0].UserName; Session["UserIDLogin"] = LogList[0].UserId; Session["UserYear"] = DateTime.Now.Year; Session["UserType"] = LogList[0].CustCode; /*---------- NOT USE * useridlogin = Convert.ToInt32(LogList[0].UserId); * if (useridlogin > 0) * { * Session["UserIDLogin"] = useridlogin; * } * ------------*/ if (LogList[0].RoleName == "Management" || LogList[0].RoleName == "ManagementUser") { return(RedirectToAction("Index", "Dashboard")); //return RedirectToAction("vNotulen", "Dashboard"); } else { ViewBag.ErrorMsg = "Not Management Roles..."; return(View()); } } } return(View()); }
private void button1_Click(object sender, EventArgs e) { if (plaintext.Text != string.Empty) { var key = GetKey(); MessageBox.Show(key); //Here key is of 128 bit //Key should be either of 128 bit or of 192 bit label1.Text = CryptoEngine.Encrypt(plaintext.Text, key); if (label1.Text != string.Empty) { //Key shpuld be same for encryption and decryption label2.Text = CryptoEngine.Decrypt(label1.Text, key); } } }