public ActionResult ChangePassword(bgce_timetracker.Models.ChangePasswordViewModel ChangePassModel) { int id = (int)Session["userID"]; var user = db.LOGINs.Where(x => x.userID == id).FirstOrDefault(); PasswordHash pass = new PasswordHash(); string userSaltString = user.password_salt; byte[] ss = Convert.FromBase64String(userSaltString); if (user.password == pass.GetHash(ChangePassModel.OldPassword, ss))//if the oldpassword matches the existing, update using NewPassword { user.password = pass.GetHash(ChangePassModel.NewPassword, ss); db.SaveChanges(); } return(RedirectToAction("Index", "Home")); }
public IActionResult Register() { var email = Request.Form["email"].ToString(); var password = Request.Form["password"].ToString(); var name = Request.Form["name"].ToString(); if ((email == "") || (password == "") || (name == "")) { return(BadRequest(new { message = "Пожалуйста, заполните все поля" })); } var user = db.Users.FirstOrDefault(x => x.Email == email); if (user != null) { return(BadRequest(new { message = "Пользователь с таким email уже зарегестрирован" })); } password = PasswordHash.GetHash(password); db.Users.Add(new User { Email = email, Password = password, Name = name }); db.SaveChanges(); return(Ok(new { message = "Вы успешно зарегистрировались" })); }
public async Task <AuthenticationUserModel> Login(LoginModel input) { try { using var unitOfWork = UnitOfWorkFactory(); _userRepository = unitOfWork.Repository <User>(); var user = await _userRepository.FindUser(input.Username.Trim()) ?? throw new AppException(AppMessages.EmailOrPasswordIncorrect); // Compare Password var hashedPassword = PasswordHash.GetHash(string.Concat(input.Password, user.Salt)); if (hashedPassword != user.Password) { throw new AppException(AppMessages.EmailOrPasswordIncorrect); } var currentUser = await _userRepository.GetCurrentUser(user.Id) ?? throw new AppException(AppMessages.Unauthorized); return(await CreateLoginResponse(currentUser, input.RememberMe, input.TimezoneOffset)); } catch (Exception e) { _logger.Error(e, e.Message); throw new AppException(e.Message); } }
private void ChangeUser() { User user; Console.WriteLine("Введите имя существующего пользователя: "); string existingUsername = Console.ReadLine(); user = users.GetUser(existingUsername); if (user == null) { Console.WriteLine("Указанный пользователь не существует"); return; } Console.Write("Введите новый пароль: "); user.Password = PasswordHash.GetHash(Console.ReadLine()); if (users.EditUser(user) == null) { Console.WriteLine("Что-то пошло не так, при изменении пароля пользователя"); } else { Console.WriteLine("Успешно завершено"); } Console.WriteLine("Нажмите любую клавишу для продолжения"); Console.ReadKey(); }
public void AddUserButton_Click(object sender, RoutedEventArgs e) { PasswordHash hash = new PasswordHash(password.Password); if (employeeID.Text.ToString() == "" || password.Password.ToString() == "") { DisplayInputError(); } else { try { if (password.Password == passwordRetype.Password) { hash.SetHash(); var hashedPW = hash.GetHash(); var salt = hash.GetSalt(); SQL.ManageDB.Add_Employee(sender, e, int.Parse(employeeID.Text), salt, hashedPW, true, DateTime.Now, 0); Frame.Navigate(typeof(LoginWindow)); } else { DisplayAddUserPasswordError(); } } catch (Exception) { Clear(); DisplayInputError(); } } }
public Task <User> Create(User data) { return(Task.Run(() => { data.Password = PasswordHash.GetHash(data.Password); User user = _db.Users.Add(data); _db.SaveChanges(); return user; })); }
//Upon Clicking Login, user is sent to the Main Page of the Application. private async void LoginButton_Click(object sender, RoutedEventArgs e) { try { PasswordHash hash = new PasswordHash(password.Password); string salt = SQL.ManageDB.Grab_Entries("Login", "Salt", "Emp_id", employeeID.Text)[0]; hash.SetHash(salt); string hashedPW = hash.GetHash(); int empID = int.Parse(employeeID.Text); if (SQL.ManageDB.CheckPassword(hashedPW, empID)) { if (SQL.ManageDB.CheckAcctActive(empID)) { SQL.ManageDB.Update_IsExpired(); SQL.ManageDB.UpdateAcctLoggedIn(empID); Frame.Navigate(typeof(Views.Shell.MainNavView), empID); } else { Clear(); ContentDialog expiredAcct = new ContentDialog { Title = "Expired User Account", Content = "The account associated with this Employee ID has expired. \nPlease contact your local Admin account holder to get your account reactivated. \n\n(Note: Accounts expire after 90 days of inactivity)", CloseButtonText = "Ok" }; ContentDialogResult result = await expiredAcct.ShowAsync(); } } else { Clear(); ContentDialog invalidLogin = new ContentDialog { Title = "Invalid Employee ID/Password", Content = "The Employee ID/Password entered is incorrect. \nPlease try again. \n\n(Hint: Check CAPS/NUM LOCK)", CloseButtonText = "Ok" }; ContentDialogResult result = await invalidLogin.ShowAsync(); } } catch (Exception) { Clear(); ContentDialog inputError = new ContentDialog { Title = "Invalid Input", Content = "One or more fields are empty or incorrect. Please enter \ninformation into all fields and try again.", CloseButtonText = "Ok" }; ContentDialogResult result = await inputError.ShowAsync(); } }
public void RenewButton_Click(object sender, RoutedEventArgs e) { PasswordHash hash = new PasswordHash(password.Password); if (employeeID.Text == "" || password.Password == "") { DisplayInputError(); } else { try { //Check if the user account exists to renew if (SQL.ManageDB.CheckEmployee(int.Parse(employeeID.Text))) { if (SQL.ManageDB.CheckAcctActive(int.Parse(employeeID.Text)) == false) { if (password.Password == passwordRetype.Password) { hash.SetHash(); var hashedPW = hash.GetHash(); var salt = hash.GetSalt(); SQL.ManageDB.Update_Employee(sender, e, int.Parse(employeeID.Text), salt, hashedPW, true, DateTime.Now); OutputSuccess.Text = "Successfully renewed Employee " + employeeID.Text + "."; OutputSuccess2.Text = "This employee now has access to this application."; Clear(); } else { Clear(); DisplayPasswordCheckError(); } } else { Clear(); DisplayUserNotExpired(); } } else { Clear(); DisplayUserNotFound(); } } catch (Exception) { Clear(); DisplayInputError(); } } }
public void AddUserButton_Click(object sender, RoutedEventArgs e) { PasswordHash hash = new PasswordHash(password.Password); if (employeeID.Text == "" || password.Password == "") { DisplayInputError(); } else { try { //If checkEmployee is false (user doesn't exist), create user account if (SQL.ManageDB.CheckEmployee(int.Parse(employeeID.Text)) == false) { if (password.Password == passwordRetype.Password) { if (privLevel == 1 || privLevel == 2) { hash.SetHash(); var hashedPW = hash.GetHash(); var salt = hash.GetSalt(); SQL.ManageDB.Add_Employee(sender, e, int.Parse(employeeID.Text), salt, hashedPW, true, DateTime.Now, privLevel); OutputSuccess.Text = "Successfully added Employee " + employeeID.Text + " to the list of authorized users for this application."; Clear(); } else { DisplayNoOptionSelected(); } } else { DisplayAddUserPasswordError(); } } else { Clear(); DisplayAddUserError(); } } catch (Exception) { Clear(); DisplayInputError(); } } }
public ActionResult AdminChangePassword(ChangePasswordViewModel ChangePassModel) { int id = (int)TempData["User"]; var user = db.LOGINs.Where(x => x.userID == id).FirstOrDefault(); PasswordHash pass = new PasswordHash(); string userSaltString = user.password_salt; byte[] ss = Convert.FromBase64String(userSaltString); user.password = pass.GetHash(ChangePassModel.NewPassword, ss); db.SaveChanges(); return(RedirectToAction("Index", "Home")); //return RedirectToAction("UserPortal", "Users"); }
public async Task <bool> AddUser(UserModel input) { using var unitOfWork = UnitOfWorkFactory(); _userRepository = unitOfWork.Repository <User>(); _userRoleRepository = unitOfWork.Repository <UserRole>(); try { if (await _userRepository.IsDuplicated(0, input.Email)) { throw new AppException(string.Format(AppMessages.ThisObjectIsExist, "Email")); } unitOfWork.BeginTransaction(); // // add to user table var salt = PasswordHash.GetSalt(); var user = new User { Email = input.Email.Trim(), Name = input.Name.Trim(), Password = PasswordHash.GetHash(string.Concat(input.Password, salt)), Salt = salt, UnitId = input.UnitId, }; await _userRepository.InsertAsync(user); // // add to userRole table await _userRoleRepository.InsertAsync(new UserRole { RoleId = input.RoleId, UserId = user.Id, IsActivated = true }); unitOfWork.CommitTransaction(); return(true); } catch (Exception e) { unitOfWork.RollbackTransaction(); _logger.Error(e, e.Message); throw new AppException(e.Message); } }
public async Task <IActionResult> Post([FromBody] RegisterModel model) { List <string> errors = new List <string>(); // is the email already used? var foundUser = _userSerivce.Get(model.Email); if (foundUser != null) { errors.Add("Email is already registered"); return(Ok(new RegisterResult { Successful = false, Errors = errors })); } else { User newUser = new User { UserName = model.Email, EmailAddress = model.Email, Password = PasswordHash.GetHash(model.Password), }; _userSerivce.Create(newUser); return(Ok(new RegisterResult { Successful = true })); } // Logic goes here to look into db to see if user exists, if not add them //var newUser = new IdentityUser { UserName = model.Email, Email = model.Email }; //var result = await _userManager.CreateAsync(newUser, model.Password); //if (!result.Succeeded) //{ // var errors = result.Errors.Select(x => x.Description); // return Ok(new RegisterResult { Successful = false, Errors = errors }); //} }
public async Task ApproveCreditApprovalRoleCashBank_ShouldReturnHttpStatusCode200AndStatusCreditFBS() { _creditApprovalController.SetUserAuth(new UserModel(new User() { Id = 4, Name = "Cash Bank", Email = "*****@*****.**", Jabatan = "Karyawan", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.CashBank })); HttpJsonApiResult <CreditApprovalModel> data = await _creditApprovalController.Approve(3, new ActionNoteRequest()) as HttpJsonApiResult <CreditApprovalModel>; Assert.AreEqual(data.StatusCode, HttpStatusCode.OK); Assert.AreEqual(data.DataValue.Status, "FBS"); }
public async Task RejectCreditApprovalRoleKomiteKredit_ShouldReturnHttpStatusCode200AndStatusCreditManagementRisiko() { _creditApprovalController.SetUserAuth(new UserModel(new User() { Id = 7, Name = "Komite Credit", Email = "*****@*****.**", Jabatan = "Karyawan", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.KomiteCredit })); HttpJsonApiResult <CreditApprovalModel> data = await _creditApprovalController.Reject(6, new ActionNoteRequest()) as HttpJsonApiResult <CreditApprovalModel>; Assert.AreEqual(data.StatusCode, HttpStatusCode.OK); Assert.AreEqual(data.DataValue.Status, "Management Risiko"); }
public async Task RejectCreditApprovalRoleAR_ShouldReturnHttpStatusCode200AndStatusCreditDraftUser() { _creditApprovalController.SetUserAuth(new UserModel(new User() { Id = 4, Name = "AR", Email = "*****@*****.**", Jabatan = "Karyawan", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.AR })); HttpJsonApiResult <CreditApprovalModel> data = await _creditApprovalController.Reject(2, new ActionNoteRequest()) as HttpJsonApiResult <CreditApprovalModel>; Assert.AreEqual(data.StatusCode, HttpStatusCode.OK); Assert.AreEqual(data.DataValue.Status, "Draft User"); }
public async Task Token() { var username = Request.Form["email"].ToString(); var password = Request.Form["password"].ToString(); password = PasswordHash.GetHash(password); var identity = getIdentity(username, password); if (identity == null) { Response.StatusCode = 400; await Response.WriteAsync("Неправильный email или пароль"); return; } var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; // сериализация ответа Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
public async Task UpdateCreditApprovalFailed_ShouldReturnHttpStatusCode404() { _creditApprovalController.SetUserAuth(new UserModel(new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Karyawan", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin })); HttpJsonApiResult <string> data = await _creditApprovalController.Update(7, new CreditApprovalRequest() { Products = new int[2] { 1, 2 } }) as HttpJsonApiResult <string>; Assert.AreEqual(data.StatusCode, HttpStatusCode.NotFound); }
public async Task CreateTrCaNoteSuccess_ShouldReturnHttpStatusCode201() { _trCaNoteController.SetUserAuth(new UserModel(new User() { Id = 5, Name = "FBS", Email = "*****@*****.**", Jabatan = "Karyawan", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.FBS })); HttpJsonApiResult <TrCaNoteModel> data = await _trCaNoteController.Post(new TrCaNoteRequest() { CreditApprovalId = 3, Perihal = "testing", Isi = "Hahahahahaha" }) as HttpJsonApiResult <TrCaNoteModel>; Assert.AreEqual(data.StatusCode, HttpStatusCode.Created); }
public async Task CreateCreditApprovalSuccess_ShouldReturnHttpStatusCode201() { _creditApprovalController.SetUserAuth(new UserModel(new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Karyawan", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin })); HttpJsonApiResult <CreditApprovalModel> data = await _creditApprovalController.Post( new CreditApprovalRequest() { Products = new int[2] { 1, 2 } }) as HttpJsonApiResult <CreditApprovalModel>; Assert.AreEqual(data.StatusCode, HttpStatusCode.Created); }
private void AddUser() { User user = new User(); do { Console.Write("Введите имя пользователя: "); user.Name = Console.ReadLine(); } while (String.IsNullOrWhiteSpace(user.Name)); Console.Write("Пароль: "); user.Password = PasswordHash.GetHash(Console.ReadLine()); if (users.AddUser(user) == null) { Console.WriteLine("Ошибка добавления пользователя. Возможно пользователь уже существует"); } else { Console.WriteLine("Пользователь успешно добавлен"); } Console.WriteLine("Нажмите любую клавишу для продолжения"); Console.ReadKey(); }
public ActionResult Create(LOGIN newuser) { if (Request.IsAuthenticated) { using (trackerEntities db = new trackerEntities()) { PasswordHash pass = new PasswordHash(); pass.Salt = pass.GenerateSalt(); newuser.userID = (int)TempData["u2"]; newuser.password = (string)TempData["pass"]; newuser.password = pass.GetHash(newuser.password, pass.Salt); newuser.password_salt = Convert.ToBase64String(pass.Salt); //int hash = newuser.password.GetHashCode(); //newuser.password_salt = hash; //password salt needs to be int ?? USER User = (USER)TempData["userModel"]; db.USERs.Add(User); //db.SaveChanges(); if (User.user_type != "Volunteer") { PAID_STAFF pAID_STAFF = (PAID_STAFF)TempData["paidStaffModel"]; db.PAID_STAFF.Add(pAID_STAFF); //db.SaveChanges(); } db.LOGINs.Add(newuser); db.SaveChanges(); } ModelState.Clear(); ViewBag.SuccessMessage = "Registration Success!"; return(RedirectToAction("Index", "Home")); } else { return(RedirectToAction("Index", "Home")); } //return View("Create", new LOGIN()); }
public async Task <bool> ChangePassword(ChangePasswordModel model) { try { using var unitOfWork = UnitOfWorkFactory(); _userRepository = unitOfWork.Repository <User>(); if (model.NewPass != model.ConfirmPass) { throw new AppException(AppMessages.PasswordIsNotSame); } var user = await _userRepository.FindUser(model.Email) ?? throw new AppException(AppMessages.EmailOrPasswordIncorrect); // Check password var hashedPassword = PasswordHash.GetHash(string.Concat(model.CurrentPass, user.Salt)); if (hashedPassword != user.Password) { throw new AppException(AppMessages.PasswordIsIncorrect); } var salt = PasswordHash.GetSalt(); user.Salt = salt; user.Password = PasswordHash.GetHash(model.NewPass, salt); await unitOfWork.SaveChangesAsync(); return(true); } catch (Exception e) { _logger.Error(e, e.Message); throw new AppException(e.Message); } }
public ActionResult Authorize(bgce_timetracker.Models.LOGIN userModel, String answer) { using (trackerEntities db = new trackerEntities()) { var userDetails = db.LOGINs.Where(x => x.username == userModel.username).ToList(); byte[] ss; string hashword; //Encoding enc = Encoding.UTF8; PasswordHash pass = new PasswordHash(); if (userDetails == null) { userModel.LoginErrorMessage = "Wrong Username"; return(View("Authorize", userModel)); } else { foreach (var item in userDetails) { string userSaltString = item.password_salt; ss = Convert.FromBase64String(userSaltString); //check the getbytes method used in the creation and login parts. make it consistant **PasswordHash.cs //pass.GetHash(item.password, ss); String password = userModel.password; if (password == null) { return(View("Authorize", userModel)); } if (item.password == pass.GetHash(userModel.password, ss)) { if (answer.Equals("Log in")) { Session["userID"] = item.userID; var timeSheet = db.TIME_SHEET.Where(x => x.active == true && x.employee == item.userID) .Select(x => x.timesheetID) .FirstOrDefault(); TempData["activeTimesheetID"] = timeSheet; var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, item.username)); var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); HttpContext.GetOwinContext().Authentication.SignIn(identity); return(RedirectToAction("Index", "Home")); } else if (answer.Equals("Punch in/out")) { Session["UserID"] = item.userID; TempData["isFoodService"] = "False"; return(RedirectToAction("punch", "TimeSheetEntry", userModel)); } else { Session["UserID"] = item.userID; TempData["isFoodService"] = "True"; return(RedirectToAction("punch", "TimeSheetEntry", userModel)); } } } } userModel.LoginErrorMessage = "Wrong Username or password"; return(View("Authorize", userModel)); } }
public void ResetButton_Click(object sender, RoutedEventArgs e) { //Checks if Admin is trying to change passwords, if true, allow changes to all empID numbers if (IsAdmin()) { PasswordHash hash = new PasswordHash(password.Password); if (employeeID.Text == "" || password.Password == "") { DisplayInputError(); } else { try { //Check if the user account exists to renew if (SQL.ManageDB.CheckEmployee(int.Parse(employeeID.Text))) { if (password.Password == passwordRetype.Password) { hash.SetHash(); var hashedPW = hash.GetHash(); var salt = hash.GetSalt(); SQL.ManageDB.Update_Employee(sender, e, int.Parse(employeeID.Text), salt, hashedPW, true, DateTime.Now); OutputSuccess.Text = "Successfully reset Employee " + employeeID.Text + "'s password."; Clear(); } else { string temp = employeeID.Text; Clear(); DisplayPasswordCheckError(); employeeID.Text = temp; } } else { Clear(); DisplayUserNotFound(); } } catch (Exception) { Clear(); DisplayInputError(); } } } //Checks if a nonAdmin is trying to change passwords, only allows change if employee is changing their own password else { PasswordHash hash = new PasswordHash(password.Password); if (employeeID.Text == "" || password.Password == "") { DisplayInputError(); } else { try { if (employeeID.Text == empID) { if (password.Password == passwordRetype.Password) { hash.SetHash(); var hashedPW = hash.GetHash(); var salt = hash.GetSalt(); SQL.ManageDB.Update_Employee(sender, e, int.Parse(employeeID.Text), salt, hashedPW, true, DateTime.Now); OutputSuccess.Text = "Password reset successfully!"; Clear(); } else { string temp = employeeID.Text; Clear(); DisplayPasswordCheckError(); employeeID.Text = temp; } } else { Clear(); DisplayNoPrivilege(); } } catch (Exception) { Clear(); DisplayInputError(); } } } }
protected override void Seed(FarmContext context) { // Диеты. Diet[] diets = { new Diet("Стол 1"), new Diet("Стол 2"), new Diet("Стол 3"), new Diet("Стол 4"), new Diet("Стол 5") }; // Породы. Breed[] breeds = { new Breed("Леггорн", 100, 10) { Diet = diets[0] }, new Breed("Хайсек Уайт", 150, 15) { Diet = diets[1] }, new Breed("Хайсек Браун", 160, 7) { Diet = diets[2] }, new Breed("Андалузская голубая", 120, 8) { Diet = diets[3] }, new Breed("Ломан Браун", 110, 12) { Diet = diets[4] } }; // Логины. Login[] logins = { new Login("qwerty1"), new Login("qwerty2"), new Login("qwerty3"), new Login("qwerty4"), new Login("qwerty5"), new Login("qwerty6"), new Login("qwerty7"), new Login("qwerty8"), new Login("qwerty9"), new Login("qwerty10") }; // Пароли. PasswordHash[] passwordHashes = { new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")), new PasswordHash(PasswordHash.GetHash("qwerty")) }; // Статусы. Status[] statuses = { new Status("Работает"), new Status("Отпуск"), new Status("Уволен") }; // Роли. Role[] roles = { new Role("Директор"), new Role("Администратор"), new Role("Работник") }; // Персоны. Person[] persons = { // Директор. new Person("Картохин", "Алексей", "Павлович", "AE2374", 250000) { Login = logins[0], PasswordHash = passwordHashes[0],Status = statuses[0], Role = roles[0] }, // Администратор. new Person("Мастерской", "Андрей", "Петрович", "AL5853", 100000) { Login = logins[1], PasswordHash = passwordHashes[1],Status = statuses[0], Role = roles[1] }, // Для работников. new Person("Лаврухин", "Пётр", "Александрович", "MA5285", 100000) { Login = logins[2], PasswordHash = passwordHashes[2],Status = statuses[0], Role = roles[0] }, new Person("Макрович", "Абрам", "Нурсултанович", "LP2245", 100000) { Login = logins[3], PasswordHash = passwordHashes[3],Status = statuses[0], Role = roles[0] }, new Person("Секретский", "Алексей", "Олегович", "ZY2856", 80000) { Login = logins[4], PasswordHash = passwordHashes[4],Status = statuses[0], Role = roles[0] }, new Person("Аргонович", "Семён", "Данилович", "ZZ8643", 50000) { Login = logins[5], PasswordHash = passwordHashes[5],Status = statuses[0], Role = roles[0] }, new Person("Нурмагомедов", "Гон", "Альбинович", "LM5286", 60000) { Login = logins[6], PasswordHash = passwordHashes[6],Status = statuses[0], Role = roles[0] }, new Person("Романский", "Роман", "Романович", "MP4912", 60000) { Login = logins[7], PasswordHash = passwordHashes[7],Status = statuses[0], Role = roles[0] }, new Person("Македонский", "Александр", "Иванович", "KK2992", 60000) { Login = logins[8], PasswordHash = passwordHashes[8],Status = statuses[0], Role = roles[0] }, new Person("Лаврентьев", "Игорь", "Никитович", "SA9878", 50000) { Login = logins[9], PasswordHash = passwordHashes[9],Status = statuses[0], Role = roles[0] } }; // Цеха. Shop[] shops = { new Shop(), new Shop(), new Shop() }; // Работники. Employee[] employees = { // Работают в 1 цехе. new Employee() { Person = persons[2] }, new Employee() { Person = persons[3] }, new Employee() { Person = persons[4] }, // Работают во 2 цехе. new Employee() { Person = persons[5] }, new Employee() { Person = persons[6] }, new Employee() { Person = persons[7] }, // Работают в 3 цехе. new Employee() { Person = persons[8] }, new Employee() { Person = persons[9] } }; // Клетки. Cell[] cells = { // Клетки для 1-го цеха. new Cell(1,1) { Shop = shops[0],Employee = employees[0] }, new Cell(1,2) { Shop = shops[0],Employee = employees[1] }, new Cell(1,3) { Shop = shops[0],Employee = employees[2] }, new Cell(1,4) { Shop = shops[0],Employee = employees[2] }, new Cell(2,2) { Shop = shops[0],Employee = employees[0] }, new Cell(2,3) { Shop = shops[0],Employee = employees[1] }, // Клетки для 2-го цеха. new Cell(1,1) { Shop = shops[1],Employee = employees[3] }, new Cell(1,2) { Shop = shops[1],Employee = employees[3] }, new Cell(1,3) { Shop = shops[1],Employee = employees[4] }, new Cell(1,4) { Shop = shops[1],Employee = employees[5] }, new Cell(2,3) { Shop = shops[1],Employee = employees[3] }, new Cell(2,4) { Shop = shops[1],Employee = employees[4] }, // Клетки для 3-го цеха. new Cell(1,1) { Shop = shops[2],Employee = employees[6] }, new Cell(1,2) { Shop = shops[2],Employee = employees[6] }, new Cell(1,3) { Shop = shops[2],Employee = employees[7] }, new Cell(1,4) { Shop = shops[2],Employee = employees[7] }, new Cell(2,1) { Shop = shops[2],Employee = employees[6] }, new Cell(2,2) { Shop = shops[2],Employee = employees[7] }, }; // Курицы. Chicken[] chickens = { new Chicken(20, 5, 30) { Breed = breeds[0],Cell = cells[0] }, new Chicken(25, 5, 30) { Breed = breeds[2],Cell = cells[1] }, new Chicken(21, 5, 30) { Breed = breeds[4],Cell = cells[2] }, new Chicken(30, 5, 30) { Breed = breeds[0],Cell = cells[3] }, new Chicken(10, 5, 30) { Breed = breeds[2],Cell = cells[4] }, new Chicken(56, 5, 30) { Breed = breeds[0],Cell = cells[5] }, new Chicken(24, 5, 30) { Breed = breeds[1],Cell = cells[6] }, new Chicken(18, 5, 30) { Breed = breeds[4],Cell = cells[7] }, new Chicken(15, 5, 30) { Breed = breeds[3],Cell = cells[8] }, new Chicken(14, 5, 30) { Breed = breeds[4],Cell = cells[9] }, new Chicken(21, 5, 30) { Breed = breeds[2],Cell = cells[10] }, new Chicken(4, 5, 30) { Breed = breeds[3],Cell = cells[11] }, }; // Отчёты. Report[] reports = { new Report(10, new DateTime(2020, 5, 9)) { Chicken = chickens[0] }, new Report(15, new DateTime(2020, 5, 10)) { Chicken = chickens[1] }, new Report(11, new DateTime(2020, 5, 11)) { Chicken = chickens[2] }, new Report(12, new DateTime(2020, 5, 12)) { Chicken = chickens[3] }, new Report(5, new DateTime(2020, 5, 13)) { Chicken = chickens[4] }, new Report(22, new DateTime(2020, 5, 15)) { Chicken = chickens[5] }, new Report(15, new DateTime(2020, 5, 17)) { Chicken = chickens[6] }, new Report(6, new DateTime(2020, 5, 19)) { Chicken = chickens[7] }, new Report(2, new DateTime(2020, 5, 20)) { Chicken = chickens[8] }, new Report(13, new DateTime(2020, 5, 21)) { Chicken = chickens[9] }, new Report(55, new DateTime(2020, 5, 23)) { Chicken = chickens[10] }, new Report(11, new DateTime(2020, 5, 28)) { Chicken = chickens[11] }, }; // Заполнение БД. foreach (var item in diets) { context.Diets.Add(item); } foreach (var item in breeds) { context.Breeds.Add(item); } foreach (var item in logins) { context.Logins.Add(item); } foreach (var item in passwordHashes) { context.PasswordHashes.Add(item); } foreach (var item in statuses) { context.Statuses.Add(item); } foreach (var item in roles) { context.Roles.Add(item); } foreach (var item in persons) { context.Persons.Add(item); } foreach (var item in shops) { context.Shops.Add(item); } foreach (var item in employees) { context.Employees.Add(item); } foreach (var item in cells) { context.Cells.Add(item); } foreach (var item in chickens) { context.Chickens.Add(item); } foreach (var item in reports) { context.Reports.Add(item); } context.SaveChanges(); } // Seed.
// Конструктор с параметрами. public LoginController(FarmContext farmContext, string login, string password) { _farmContext = farmContext; _login = login; _password = PasswordHash.GetHash(password); } // ctorf.
public void LoadDummyData() { #region user dummy data Users.Add(new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Komisaris", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin }); Users.Add(new User() { Id = 2, Name = "AR", Email = "*****@*****.**", Jabatan = "Management Resiko", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.AR }); Users.Add(new User() { Id = 3, Name = "User", Email = "*****@*****.**", Jabatan = "Karyawan", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.User }); Users.Add(new User() { Id = 4, Name = "FBS", Email = "*****@*****.**", Jabatan = "Keuangan", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.FBS }); #endregion #region customer dummy data Customers.Add(new Customer() { Id = 1, CustomerNo = "1236969", Name = "PT Kera Sakti", Email = "*****@*****.**", Address = "Gunung kayangan", NPWP = "01010169" }); Customers.Add(new Customer() { Id = 2, CustomerNo = "4616111", Name = "Cv Kamehameha Batam", Email = "*****@*****.**", Address = "Pulau roshi", NPWP = "222333444" }); Customers.Add(new Customer() { Id = 3, CustomerNo = "3456789", Name = "PT Santai Menyantai", Email = "*****@*****.**", Address = "Jalan malas", NPWP = "55667788" }); Customers.Add(new Customer() { Id = 4, CustomerNo = "3456789", Name = "PT Ninja Gadungan", Email = "*****@*****.**", Address = "Konohahaha", NPWP = "777888999" }); #endregion #region product dummy data Products.Add(new Product() { Id = 1, MaterialNo = "001", MaterialName = "Premium", MaterialGroup = "001" }); Products.Add(new Product() { Id = 2, MaterialNo = "002", MaterialName = "Pertalite", MaterialGroup = "002" }); Products.Add(new Product() { Id = 3, MaterialNo = "003", MaterialName = "Solar", MaterialGroup = "003" }); Products.Add(new Product() { Id = 4, MaterialNo = "004", MaterialName = "Pertamax", MaterialGroup = "004" }); #endregion #region signature dummy data Signatures.Add(new Signature() { Id = 1, Name1 = "Basuki cahaya purnama", Name2 = "Eric Thoir", Position1 = "Komisaris Utama", Position2 = "Menteri BUMN", DocumentType = "CA" }); Signatures.Add(new Signature() { Id = 2, Name1 = "Goku", Name2 = "Vegeta", Position1 = "Earth Saiyan", Position2 = "Prince Saiyan", DocumentType = "CA" }); Signatures.Add(new Signature() { Id = 3, Name1 = "Ramen", Name2 = "Burger", Position1 = "Japanese Noodle", Position2 = "USA Sandwich", DocumentType = "CA" }); Signatures.Add(new Signature() { Id = 4, Name1 = "PUBG", Name2 = "Mobile Legend", Position1 = "Battle Royale", Position2 = "Moba", DocumentType = "CA" }); #endregion #region credit approval dummy data CreditApprovals.Add(new CreditApproval() { Id = 1, TicketNumber = "44667788", MailNumber = "1122334455", CustomerId = 3, TempoStart = Convert.ToDateTime("01/12/2019"), TempoEnd = Convert.ToDateTime("05/05/2020"), LongTempo = "Perbulan 1 kali", Volume = "2 Liter", Units = "Per Kg", PeriodeVolume = "Perbulan Volume", SubmissionPeriod = "Kapan Saja", TransactionValue = "Rp 2.000.000", CreditLimit = "Rp 2.500.000", Payment = "Bank Indonesia", Guarantee = "BPOM", Status = EStatusCredit.DraftUser, FlagRead = true, FlagFine = true, CreatedBy = 1, Currency = "Rp", TransactionValueEstimatedPeriod = "Perbulan Pengeluaran", TrCaActionNote = new List <TrCaActionNote>(), TrCaProducts = new List <TrCaProduct>(), TrCaNotes = new List <TrCaNote>(), CaCustomerDetails = new List <CaCustomerDetail>(), QuantitativeAspects = new List <QuantitativeAspect>(), CreditScorings = new List <CreditScoring>(), User = new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Komisaris", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin } }); CreditApprovals.Add(new CreditApproval() { Id = 2, TicketNumber = "44667788", MailNumber = "1122334455", CustomerId = 2, TempoStart = Convert.ToDateTime("01/12/2019"), TempoEnd = Convert.ToDateTime("05/05/2020"), LongTempo = "Perbulan 1 kali", Volume = "2 Liter", Units = "Per Kg", PeriodeVolume = "Perbulan Volume", SubmissionPeriod = "Kapan Saja", TransactionValue = "Rp 2.000.000", CreditLimit = "Rp 2.500.000", Payment = "Bank Indonesia", Guarantee = "BPOM", Status = EStatusCredit.AR, FlagRead = true, FlagFine = true, CreatedBy = 1, Currency = "Rp", TransactionValueEstimatedPeriod = "Perbulan Pengeluaran", TrCaActionNote = new List <TrCaActionNote>(), TrCaProducts = new List <TrCaProduct>(), TrCaNotes = new List <TrCaNote>(), CaCustomerDetails = new List <CaCustomerDetail>(), QuantitativeAspects = new List <QuantitativeAspect>(), CreditScorings = new List <CreditScoring>(), User = new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Komisaris", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin } }); CreditApprovals.Add(new CreditApproval() { Id = 3, TicketNumber = "44667788", MailNumber = "1122334455", CustomerId = 1, TempoStart = Convert.ToDateTime("01/12/2019"), TempoEnd = Convert.ToDateTime("05/05/2020"), LongTempo = "Perbulan 1 kali", Volume = "2 Liter", Units = "Per Kg", PeriodeVolume = "Perbulan Volume", SubmissionPeriod = "Kapan Saja", TransactionValue = "Rp 2.000.000", CreditLimit = "Rp 2.500.000", Payment = "Bank Indonesia", Guarantee = "BPOM", Status = EStatusCredit.CashBank, FlagRead = true, FlagFine = true, CreatedBy = 1, Currency = "Rp", TransactionValueEstimatedPeriod = "Perbulan Pengeluaran", TrCaActionNote = new List <TrCaActionNote>(), TrCaProducts = new List <TrCaProduct>(), TrCaNotes = new List <TrCaNote>(), CaCustomerDetails = new List <CaCustomerDetail>(), QuantitativeAspects = new List <QuantitativeAspect>(), CreditScorings = new List <CreditScoring>(), User = new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Komisaris", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin } }); CreditApprovals.Add(new CreditApproval() { Id = 4, TicketNumber = "44667788", MailNumber = "1122334455", CustomerId = 4, TempoStart = Convert.ToDateTime("01/12/2019"), TempoEnd = Convert.ToDateTime("05/05/2020"), LongTempo = "Perbulan 1 kali", Volume = "2 Liter", Units = "Per Kg", PeriodeVolume = "Perbulan Volume", SubmissionPeriod = "Kapan Saja", TransactionValue = "Rp 2.000.000", CreditLimit = "Rp 2.500.000", Payment = "Bank Indonesia", Guarantee = "BPOM", Status = EStatusCredit.FBS, FlagRead = true, FlagFine = true, CreatedBy = 1, Currency = "Rp", TransactionValueEstimatedPeriod = "Perbulan Pengeluaran", TrCaActionNote = new List <TrCaActionNote>(), TrCaProducts = new List <TrCaProduct>(), TrCaNotes = new List <TrCaNote>(), CaCustomerDetails = new List <CaCustomerDetail>(), QuantitativeAspects = new List <QuantitativeAspect>(), CreditScorings = new List <CreditScoring>(), User = new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Komisaris", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin } }); CreditApprovals.Add(new CreditApproval() { Id = 5, TicketNumber = "44667788", MailNumber = "1122334455", CustomerId = 2, TempoStart = Convert.ToDateTime("01/12/2019"), TempoEnd = Convert.ToDateTime("05/05/2020"), LongTempo = "Perbulan 1 kali", Volume = "2 Liter", Units = "Per Kg", PeriodeVolume = "Perbulan Volume", SubmissionPeriod = "Kapan Saja", TransactionValue = "Rp 2.000.000", CreditLimit = "Rp 2.500.000", Payment = "Bank Indonesia", Guarantee = "BPOM", Status = EStatusCredit.ManagementRisk, FlagRead = true, FlagFine = true, CreatedBy = 1, Currency = "Rp", TransactionValueEstimatedPeriod = "Perbulan Pengeluaran", TrCaActionNote = new List <TrCaActionNote>(), TrCaProducts = new List <TrCaProduct>(), TrCaNotes = new List <TrCaNote>(), CaCustomerDetails = new List <CaCustomerDetail>(), QuantitativeAspects = new List <QuantitativeAspect>(), CreditScorings = new List <CreditScoring>(), User = new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Komisaris", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin } }); CreditApprovals.Add(new CreditApproval() { Id = 6, TicketNumber = "44667788", MailNumber = "1122334455", CustomerId = 1, TempoStart = Convert.ToDateTime("01/12/2019"), TempoEnd = Convert.ToDateTime("05/05/2020"), LongTempo = "Perbulan 1 kali", Volume = "2 Liter", Units = "Per Kg", PeriodeVolume = "Perbulan Volume", SubmissionPeriod = "Kapan Saja", TransactionValue = "Rp 2.000.000", CreditLimit = "Rp 2.500.000", Payment = "Bank Indonesia", Guarantee = "BPOM", Status = EStatusCredit.KomiteCredit, FlagRead = true, FlagFine = true, CreatedBy = 1, Currency = "Rp", TransactionValueEstimatedPeriod = "Perbulan Pengeluaran", TrCaActionNote = new List <TrCaActionNote>(), TrCaProducts = new List <TrCaProduct>(), TrCaNotes = new List <TrCaNote>(), CaCustomerDetails = new List <CaCustomerDetail>(), QuantitativeAspects = new List <QuantitativeAspect>(), CreditScorings = new List <CreditScoring>(), User = new User() { Id = 1, Name = "Admin", Email = "*****@*****.**", Jabatan = "Komisaris", Password = PasswordHash.GetHash("12345678"), Role = EUserRole.Admin } }); #endregion #region tr ca note dummy data TrCaNotes.Add(new TrCaNote() { Id = 1, CreditApprovalId = 1, TanggalNota = Convert.ToDateTime("12/12/2019"), Perihal = "Pesan Dari FBS", Isi = "Data ini valid", CreatedBy = "Admin", CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now }); TrCaNotes.Add(new TrCaNote() { Id = 2, CreditApprovalId = 2, TanggalNota = Convert.ToDateTime("12/12/2019"), Perihal = "Pesan Dari FBS", Isi = "Data ini valid", CreatedBy = "Admin", CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now }); TrCaNotes.Add(new TrCaNote() { Id = 3, CreditApprovalId = 3, TanggalNota = Convert.ToDateTime("12/12/2019"), Perihal = "Pesan Dari FBS", Isi = "Data ini valid", CreatedBy = "Admin", CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now }); #endregion }