private void btnChangePassword_Click(object sender, EventArgs e) { if (lbUsers.SelectedItem == null) { MessageBox.Show("Please select a user"); return; } UserPrincipal insUserPrincipal = (UserPrincipal)lbUsers.SelectedItem; UserPassword password = new UserPassword(); frmProperties insFrmProperties = new frmProperties(password, ActionTypes.Save); insFrmProperties.ShowDialog(); if (insFrmProperties.DialogResult == DialogResult.OK) { try { insUserPrincipal.SetPassword(password.Password); MessageBox.Show("Password changed."); } catch (Exception ex) { MessageBox.Show(ex.Message); } ListUsers(); } }
private async void ExecutePatternAsync(object item) { Pattern selectedPattern = item as Pattern; UserPassword.Value = await Application.Current.MainPage.DisplayPromptAsync("Подтверждение перевода", "Введите пароль"); if (UserPassword.Value == null) { return; } if (UserPassword.Validate()) { Tuple <bool, string> responseCheck = await UserService.Instance.Login(App.GetUser().login, UserPassword.Value); if (responseCheck.Item1 == true) { string response = await TransactionService.Instance.DoTransfer(selectedPattern.from_, selectedPattern.to_, selectedPattern.amount); await Application.Current.MainPage.DisplayAlert("Message", response, "OK"); } else { await Application.Current.MainPage.DisplayAlert("Message", "Неправильно введен пароль", "OK"); } } }
/// <summary> /// Smart-me API Calls with Basic Authentication. /// </summary> /// <param name="usernamePassword">The Username and Password for Basic Authentication</param> public SmartMeApiClient(UserPassword usernamePassword) { this.CreateClient(); var byteArray = Encoding.ASCII.GetBytes(usernamePassword.Username + ":" + usernamePassword.Password); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); }
public ActionResult LogIn(LoginViewModel login) { if (ModelState.IsValid) { UserPassword model = userPasswordDal.GetUser(login.Username); if (model == null) { ModelState.AddModelError("invalid username", "The username or password provided is invalid"); return(View("LogIn", login)); } if (model.Password != login.Password) { ModelState.AddModelError("invalid pwd", "The username or password provided is invalid"); return(View("LogIn", login)); } //happy path base.LogUserIn(model.Username); return(RedirectToAction("Index", model.RoleTitle, new { username = model.Username })); } else { return(View("LogIn", login)); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); var optionsBuilder = new DbContextOptionsBuilder <MyDbContext>().UseSqlite(Configuration.GetConnectionString("Sqlite")); using (var myDbContext = new MyDbContext(optionsBuilder.Options)) { var user = myDbContext.Users.FirstOrDefault(); if (user == null) { User firstUser = new User() { Id = Guid.NewGuid(), Name = "teste", Email = "*****@*****.**", }; firstUser.Validate(); myDbContext.Users.Add(firstUser); UserPassword userPassword = new UserPassword() { Id = firstUser.Id, UserId = firstUser.Id, Password = Cryptography.Encrypt(firstUser.Email + "teste"), }; userPassword.Validate(); myDbContext.UsersPassword.Add(userPassword); myDbContext.SaveChanges(); } } }
public async Task <IActionResult> ChangePassword([FromBody] UserPassword user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (user.NewPassword != user.ReNewPassword) { return(BadRequest(ModelState)); } var dbUser = _context.Users.FirstOrDefault(u => u.Id == user.Id); if (dbUser == null) { return(BadRequest(ModelState)); } PasswordHasher <User> hasher = new PasswordHasher <User>(); var result = hasher.VerifyHashedPassword(dbUser, dbUser.Password, user.OldPassword); if (result != PasswordVerificationResult.Success) { return(BadRequest(ModelState)); } dbUser.Password = hasher.HashPassword(dbUser, user.NewPassword); await _context.SaveChangesAsync(); return(Ok(dbUser.Id)); }
public ActionResult Create([Bind(Include = "Nome,UserName,FisJur,Telefone,Senha,ConfirmSenha")] Users users) { Vendedor vendedor = new Vendedor(); Comprador comprador = new Comprador(); UserPassword password = new UserPassword(); if (ModelState.IsValid) { users = InsertUser(users); vendedor.IdUser = users.Id; InsertVendedor(vendedor); comprador.IdUser = users.Id; InsertComprador(comprador); password.Id = users.Id; password.Password = users.Senha; password.PasswordConfirm = users.ConfirmSenha; InsertPassword(password); return(RedirectToAction("Login", "Home", new { area = "" })); } ViewData["FisicaJuridica"] = ReadFisicaJuridica(); return(View()); }
private void InsertPassword(UserPassword userPassword) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ConfigurationSettings.AppSettings["URLUserPassword"]); HttpWebResponse response; StreamWriter sw; clsJSONFormatter formatter = new clsJSONFormatter(); string strJSON = ""; try { strJSON = formatter.ClasstoJSON(userPassword); request.ContentType = "application/json"; request.Accept = "application/json"; request.Method = "POST"; request.KeepAlive = false; sw = new StreamWriter(request.GetRequestStream()); sw.Write(strJSON); sw.Flush(); response = (HttpWebResponse)request.GetResponse(); request.Abort(); response.Close(); response.Dispose(); sw.Close(); sw.Dispose(); } catch (Exception ex) { throw new Exception(ex.Message); } }
private void initCurl(string url) { easy = new CurlEasy(); easy.Url = url; easy.Timeout = TimeOut; easy.ConnectTimeout = TimeOut; easy.BufferSize = BLOCK_SIZE; if ((!UserName.Equals("")) && (!UserPassword.Equals(""))) { easy.SetOpt(CurlOption.UserPwd, UserName + ":" + UserPassword); } // easy.fun easy.DebugFunction = OnDebug; easy.ProgressFunction = onProgress; easy.UserAgent = "curl"; easy.Verbose = true; // HTTP/2 please // easy.HttpVersion = CurlHttpVersion.Http2_0; // skip SSL verification during debugging easy.SslVerifyPeer = false; easy.SslVerifyhost = false; easy.SetOpt(CurlOption.HttpHeader, "Content-Type: application/octet-stream"); easy.SetOpt(CurlOption.HttpHeader, "Expect:"); }
public static async Task FolderAsync(UserPassword credentials) { // Get Folder { Helpers.WriteConsoleTitle("Get Folder"); var folder = await FolderApi.GetFolderAsync(credentials, new Guid("686e51c1-2df8-4596-88aa-113f9022474a")); Console.WriteLine($"ElectricityCounterValue: {folder.ElectricityCounterValue}, ElectricityPower: {folder.ElectricityPower}"); } // Get MeterFolderInformation { Helpers.WriteConsoleTitle("Get MeterFolderInformation"); var info = await FolderApi.GetMeterFolderInformationAsync(credentials, new Guid("d9cc91af-58a1-48ed-9342-4aaf974074f2")); Console.WriteLine($"Name: {info.Name}, IsFolder: {info.IsFolder}"); } // Set MeterFolderInformation { Helpers.WriteConsoleTitle("Set MeterFolderInformation"); await FolderApi.SetMeterFolderInformationAsync(credentials, new MeterFolderInformationToSet { Id = new Guid("d9cc91af-58a1-48ed-9342-4aaf974074f2"), Name = "Test" }); } }
public CustomGoogleDetails Post([FromBody] CustomGoogleDetails value) { char[] sep = { '.' }; string[] username = value.Email.Split(sep, 2, StringSplitOptions.None); var entity = db.UserDetails.Where(s => s.Username == username[0]).ToList(); if (entity.Count() == 0) { UserPassword userPassword = new UserPassword { Username = username[0], Password = value.Password }; UserDetails userDetails = new UserDetails { Username = username[0], Email = value.Email }; db.UserPassword.Add(userPassword); db.UserDetails.Add(userDetails); db.SaveChanges(); return(value); } return(value); }
private async Task AddPassword(string newPassword, User user) { var userPassword = new UserPassword() { User = user, PasswordFormat = UserSettings.DefaultPasswordFormat, CreatedOnUtc = DateTime.UtcNow }; switch (UserSettings.DefaultPasswordFormat) { case PasswordFormat.Clear: userPassword.Password = newPassword; break; case PasswordFormat.Encrypted: userPassword.Password = _encryptionService.EncryptText(newPassword); break; case PasswordFormat.Hashed: { var saltKey = _encryptionService.CreateSaltKey(5); userPassword.PasswordSalt = saltKey; userPassword.Password = _encryptionService.CreatePasswordHash(newPassword, saltKey, UserSettings.HashedPasswordFormat); } break; } UserService.InsertUserPassword(userPassword); await UserService.UpdateUserAsync(user); }
/// <summary> /// Gets all Custom Devices /// </summary> /// <param name="usernamePassword">The Username and Password for Basic Authentication</param> /// <returns></returns> public static async Task <List <CustomDevice> > GetCustomDevicesAsync(UserPassword usernamePassword) { using (var restApi = new SmartMeApiClient(usernamePassword)) { return(await restApi.GetAsync <List <CustomDevice> >("CustomDevice")); } }
/// <summary> /// Gets a Custom Device by it's ID /// </summary> /// <param name="usernamePassword">The Username and Password for Basic Authentication</param> /// <param name="deviceId">The ID of the device</param> /// <returns></returns> public static async Task <CustomDevice> GetCustomDeviceAsync(UserPassword usernamePassword, Guid deviceId) { using (var restApi = new SmartMeApiClient(usernamePassword)) { return(await restApi.GetAsync <CustomDevice>("CustomDevice/" + deviceId)); } }
/// <summary> /// Gets the available Folders or Meters /// </summary> /// <param name="usernamePassword">The Username and Password for Basic Authentication</param> /// <param name="id">The ID of the Folder or Meter</param> /// <returns></returns> public static async Task <Folder> GetFolderAsync(UserPassword usernamePassword, Guid id) { using (var restApi = new SmartMeApiClient(usernamePassword)) { return(await restApi.GetAsync <Folder>("Folder/" + id)); } }
/// <summary> /// Sets the configuration of a smart-me device. The device needs to be online. /// </summary> /// <param name="usernamePassword">The Username and Password for Basic Authentication</param> /// <param name="configuration">The smart-me device configuration</param> /// <returns></returns> public static async Task <bool> SetSmartMeDeviceConfigurationAsync(UserPassword usernamePassword, SmartMeDeviceConfiguration configuration) { using (var restApi = new SmartMeApiClient(usernamePassword)) { return(await restApi.PostAsync <SmartMeDeviceConfiguration>("SmartMeDeviceConfiguration", configuration)); } }
public IActionResult Post([FromBody] CustomJoinedDetails val) { var entity = db.UserDetails.Where(s => s.Email == val.Email || s.Username == val.Username).ToList(); if (entity.Count() == 0) { var hashedPassword = BCrypt.Net.BCrypt.HashPassword(val.Password); UserPassword userPassword = new UserPassword { Username = val.Username, Password = hashedPassword }; UserDetails userDetails = new UserDetails { Email = val.Email, CollegeId = val.CollegeId, CollegeName = val.CollegeName, UsernameNavigation = userPassword }; db.UserDetails.Add(userDetails); db.SaveChanges(); return(Ok(true)); } else if (entity[0].Username == val.Username) { return(BadRequest("Username already Existed")); } else { return(BadRequest("Email ID already Existed")); } }
public ActionResult Login(LoginViewModel vm) { if (ModelState.IsValid) { if (UserPassword.ValidateUser(vm.UserName, vm.Password, Db)) { Authentication auth = new Authentication(); OsbideUser user = Db.Users.Where(u => u.Email.CompareTo(vm.UserName) == 0).FirstOrDefault(); if (user != null) { auth.LogIn(user); //did the user come from somewhere? if (string.IsNullOrEmpty(vm.ReturnUrl) == false) { Response.Redirect(vm.ReturnUrl); } return(RedirectToAction("Index", "Profile")); } } } //if we got this far, must've had a bad user name or password ModelState.AddModelError("", "Invalid email or password."); return(View()); }
/// <summary> /// Check whether the entered password matches with saved one /// </summary> /// <param name="UserPassword">User password</param> /// <param name="enteredPassword">The entered password</param> /// <returns>True if passwords match; otherwise false</returns> protected bool PasswordsMatch(UserPassword UserPassword, string enteredPassword) { if (UserPassword == null || string.IsNullOrEmpty(enteredPassword)) { return(false); } var savedPassword = string.Empty; switch (UserPassword.PasswordFormat) { case PasswordFormat.Clear: savedPassword = enteredPassword; break; case PasswordFormat.Encrypted: savedPassword = _encryptionService.EncryptText(enteredPassword); break; case PasswordFormat.Hashed: savedPassword = _encryptionService.CreatePasswordHash(enteredPassword, UserPassword.PasswordSalt, _UserSettings.HashedPasswordFormat); break; } return(UserPassword.Password.Equals(savedPassword)); }
public ActionResult CreateUser(UserModal user) { Result <UserCpf> cpf = UserCpf.Create(user.cpf); Result <UserPassword> password = UserPassword.Create(user.password); Result <UserCardNumber> cardNumber = UserCardNumber.Create(user.cardNumber); Result <UserCardDigits> cardDigits = UserCardDigits.Create(user.cardDigits); Result <UserCardDate> cardDate = UserCardDate.Create(user.cardDate); Result result = Result.Combine(cpf, password, cardDate, cardDigits, cardNumber); if (result.IsNotSuccess) { return(new BadRequestObjectResult(result.Error)); } User newUser = new User(cpf.Value, cardDate.Value, cardDigits.Value, cardNumber.Value, password.Value); var createUserOperation = _userService.CreateUser(newUser); if (createUserOperation.IsNotSuccess) { return(new BadRequestObjectResult(createUserOperation.Error)); } return(new OkResult()); }
public UserPassword GetUser(string username) { UserPassword output = null; try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(SQL_GetUserByUsername, conn); cmd.Parameters.AddWithValue("@username", username); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { output = new UserPassword(); output.Username = Convert.ToString(reader["username"]); output.Password = Convert.ToString(reader["password"]); output.RoleTitle = Convert.ToString(reader["role_title"]); } } } catch (SqlException ex) { throw; } return(output); }
public async Task <IHttpActionResult> Reset(AccountEmailReset model) { var user = await AppDatabase.Users.FirstOrDefaultAsync(o => o.Email == model.Email); if (user == null) { return(BadRequest("User not found")); } if (string.IsNullOrEmpty(user.Email)) { return(BadRequest("User lacks a valid email address. Did you use Facebook or Twilio ?")); } var token = Strings.RandomString(6).ToLower(); user.ModifiedOn = DateTime.UtcNow; user.EmailPassword = UserPassword.Create(token); AppDatabase.Entry(user).State = EntityState.Modified; await AppDatabase.SaveChangesAsync(); await SendTokenEmail(new UserTokenViewModel { UserId = user.Id, UserEmail = user.Email, Token = token, }); return(Ok(GetAccountDetails())); }
public IHttpActionResult PostUser(UserPassword userPassword) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = new User { Address = userPassword.Address, FirstName = userPassword.FirstName, IsStudent = true, IsTeacher = false, LastName = userPassword.LastName, Phone = userPassword.Phone, UserName = userPassword.UserName, }; try { db.Users.Add(user); db.SaveChanges(); Utilities.CreateUserASP(userPassword.UserName, "Student", userPassword.Password); } catch (Exception ex) { return(this.BadRequest(ex.Message)); } userPassword.UserId = user.UserId; userPassword.IsStudent = true; userPassword.IsTeacher = false; return(this.Ok(userPassword)); }
protected void Confirm_OnClick(object sender, EventArgs e) { //验证码检验 if (!txtCaptcha.Text.Equals(Session["code"])) { Response.Write("<script>alert('验证码错误!')</script>"); return; } // 用LoginController进行登录检验 try { //订阅登录结果分支事件 LoginController.LoginSuccess += LoginSuccess; LoginController.LoginFailure += LoginFailure; var login = new LoginController(UserID.Text, UserPassword.Text); } catch (LoginErrorException et) { if (et.Message == "密码错误!") { Response.Write($"<script>alert('密码错误!这是第{Session["Time"]}次错误!')</script>"); Session["Time"] = Int32.Parse(Session["Time"].ToString()) + 1; UserPassword.Focus(); } } }
protected void ValidateFull() { if (string.IsNullOrEmpty(UserName.Trim())) { LocalFunctions.AddError("Please enter user name", MethodBase.GetCurrentMethod(), false, false); } else if (UserName.Trim().Length < 3) { LocalFunctions.AddError("User name should contain minimum 6 characters", MethodBase.GetCurrentMethod(), false, false); } else if (UserName.Trim().Length > 100) { LocalFunctions.AddError("User name can contain maximum 100 characters", MethodBase.GetCurrentMethod(), false, false); } if (string.IsNullOrEmpty(UserPassword.Trim())) { LocalFunctions.AddError("Please enter password", MethodBase.GetCurrentMethod(), false, false); } else if (UserPassword.Trim().Length < 6) { LocalFunctions.AddError("Password should contain minimum 6 characters", MethodBase.GetCurrentMethod(), false, false); } else if (UserPassword.Trim().Length > 30) { LocalFunctions.AddError("Password should contain maximum 30 characters", MethodBase.GetCurrentMethod(), false, false); } }
public ActionResult Create([Bind(Include = "Id,Password,PasswordConfirm")] UserPassword userPassword) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ConfigurationSettings.AppSettings["URLUserPassword"]); HttpWebResponse response; StreamWriter sw; clsJSONFormatter formatter = new clsJSONFormatter(); string strJSON = ""; if (ModelState.IsValid) { strJSON = formatter.ClasstoJSON(userPassword); request.ContentType = "application/json"; request.Accept = "application/json"; request.Method = "POST"; request.KeepAlive = false; sw = new StreamWriter(request.GetRequestStream()); sw.Write(strJSON); sw.Flush(); response = (HttpWebResponse)request.GetResponse(); request.Abort(); response.Close(); sw.Dispose(); return(RedirectToAction("Details", "UsersMVC", new { id = userPassword.Id })); } request.Abort(); return(RedirectToAction("Details", "UsersMVC", new { id = userPassword.Id })); }
public async Task <IActionResult> PutUser(int id, UserPassword userPass) { if (id != userPass.idUser) { return(BadRequest("User changed is not the same as the user logged in!")); } userPass.Password = HashMd5Generator.Generate(userPass.Password); var user = new User() { idUser = userPass.idUser, Password = userPass.Password }; _context.Entry(user).Property(x => x.Password).IsModified = true; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException ex) { if (!UserExists(id)) { return(NotFound("User not found!")); } else { return(StatusCode(500, ex.Message)); } } return(NoContent()); }
public ActionResult Generate(UserPasswordDTO userPasswordDTO) { UserPassword userPassword = _passwordBL.GeneratePassword(_mapper.Map <UserPassword>(userPasswordDTO)); UserPasswordDTO upDTO = _mapper.Map <UserPasswordDTO>(userPassword); return(View("Validate", upDTO)); }
/// <summary> /// Sets the Name of a Meter or a Folder /// </summary> /// <param name="usernamePassword">The Username and Password for Basic Authentication</param> /// <param name="meterFolderInformation">The Id of the meter or folder and the Name to be set</param> /// <returns></returns> public static async Task <bool> SetMeterFolderInformationAsync(UserPassword usernamePassword, MeterFolderInformationToSet meterFolderInformation) { using (var restApi = new SmartMeApiClient(usernamePassword)) { return(await restApi.PostAsync <MeterFolderInformationToSet>("MeterFolderInformation", meterFolderInformation)); } }
public IActionResult EditPassword(int userId, UserPassword editForm) { int? loggedId = HttpContext.Session.GetInt32("LoggedId"); User updateUser = _context.Users.FirstOrDefault(u => u.UserId == userId); if (ModelState.IsValid) { PasswordHasher <UserPassword> hasher = new PasswordHasher <UserPassword>(); updateUser.Password = hasher.HashPassword(editForm, editForm.Password); updateUser.UpdatedAt = DateTime.Now; _context.SaveChanges(); return(RedirectToAction("Dashboard")); } else { ViewBag.Logged = true; if ((int)loggedId == userId) { ViewBag.Admin = false; } else { ViewBag.Admin = true; } ViewBag.UserId = userId; return(View("UserProfile", updateUser)); } }
public UserPasswordBatch(UserPassword[] userAnswers, int batchId) { UserAnswers = userAnswers; BatchId = batchId; }