public async Task <AdminAccount> InsertAdmin(AdminAccount admin) { var parameters = new SqlParameter[] { new SqlParameter("adminId", admin.AdminId), new SqlParameter("creatorId", admin.CreatorId), new SqlParameter("adminFirstName", admin.AdminFirstName), new SqlParameter("adminLastName", admin.AdminLastName), new SqlParameter("adminEmail", admin.AdminEmail), new SqlParameter("adminPhoneNumber", admin.AdminPhoneNumber), new SqlParameter("adminPassword", admin.AdminPassword), new SqlParameter("salt", admin.Salt), new SqlParameter("adminBirthday", admin.AdminBirthday), new SqlParameter("adminGender", admin.AdminGender), new SqlParameter("adminRights", admin.AdminRights) }; try { await _db.Database.ExecuteSqlRawAsync("sp_insertAdmin @adminId,@creatorId, @adminFirstName, @adminLastName, " + "@adminEmail, @adminPhoneNumber, @adminPassword, @salt, @adminBirthday, @adminGender,@adminRights", parameters); return(admin); }catch (Exception ex) { Console.WriteLine(ex); } return(null); }
public async Task <AdminAccount> EditAdmin(AdminAccount admin) { var adminAcc = await _db.AdminAccount.FindAsync(admin.AdminId); if (adminAcc == null) { return(null); } var parameters = new SqlParameter[] { new SqlParameter("adminId", admin.AdminId), new SqlParameter("adminFirstName", admin.AdminFirstName), new SqlParameter("adminLastName", admin.AdminLastName), new SqlParameter("adminBirthday", admin.AdminBirthday), new SqlParameter("adminGender", admin.AdminGender), new SqlParameter("adminRights", admin.AdminRights) }; try { await _db.Database.ExecuteSqlRawAsync("sp_updateAdmin @adminId, @adminFirstName, @adminLastName, @adminBirthday, @adminGender, @adminRights", parameters); return(adminAcc); } catch (Exception ex) { Console.WriteLine(ex); } return(null); }
private void FormAdminAccountCE_Load(object sender, EventArgs e) { // Neu la che do chinh sua (Edit) thi hien thi thong tin cua account len form if (mode == FormMode.EDIT) { txtUsername.Text = adminAccount.Username; txtPassword.Text = adminAccount.Password; txtName.Text = adminAccount.Name; txtRole.Text = adminAccount.Role; if (adminAccount.IsActive) { // Neu tai khoan nay dang active thi check vao radio button Active rbtnActive.Checked = true; } else { rbtnInActive.Checked = true; } } else { // Neu dang o che do them moi // Tao moi mot account adminAccount = new AdminAccount(); // Gan gia tri mac dinh cho ID (ID no se tu tang nen minh khong can phai tao) adminAccount.ID = 0; // Nhung gia tri khac se duoc gan vao account khi nguoi dung bam nut Submit } }
public async Task <AdminAccount> GetAdminAccountAsync(AdminAccount adminAccount) { using (ParkingLotManagementContext context = new ParkingLotManagementContext()) { return(await context.AdminAccount.FindAsync(adminAccount.ID)); } }
public ActionResult Index(IEnumerable <string> firstname, IEnumerable <string> lastname, IEnumerable <string> email) { if (AuthTokens[0] == "demo") { ViewBag.DemoNextStep = NextStep("!"); return(View()); } if (firstname != null && lastname != null && email != null) { if (firstname.Count() == lastname.Count() && firstname.Count() == email.Count()) { CounselorInviteClient cic = new CounselorInviteClient(); AdminAccountClient aac = new AdminAccountClient(); UserAccountClient uac = new UserAccountClient(); AdminAccount admin = aac.GetByPartitionAndRowKey("admin", AuthTokens[1].ToLower()); UserAccount user = uac.GetByPartitionAndRowKey(UserAccountClient.GetPartitionKeyForEmail(AuthTokens[1].ToLower()), AuthTokens[1].ToLower()); string school = admin.School; for (var i = 0; i < firstname.Count(); i++) { string emailLower = email.ElementAt(i).ToLower(); string guid = ShortGuidGenerator.NewGuid(); cic.AddNewItem(new CounselorInvite { FirstName = firstname.ElementAt(i), LastName = lastname.ElementAt(i), Email = emailLower, School = school, RowKey = guid }); SendInviteEmail(email.ElementAt(i).ToLower(), firstname.ElementAt(i) + " " + lastname.ElementAt(i), user.FirstName + " " + user.LastName, guid); } return(View()); } } ViewBag.ErrorMessage = "error"; return(View()); }
public static dynamic GetUserWithTypeFromPassword(UserAccount userAccount, string password) { if (userAccount.Password == password) { using (var dbContext = new InventoryContext()) { if (userAccount.IsAdmin) { AdminAccount user = (from admin in dbContext.UserAccounts.OfType <AdminAccount>() where admin.Username == userAccount.Username select admin).First(); return(user); } else { StaffAccount user = (from staff in dbContext.UserAccounts.OfType <StaffAccount>() where staff.Username == userAccount.Username select staff).First(); return(user); } } } else { return(null); } }
public ActionResult Groups(IEnumerable <string> year, IEnumerable <string> grade, IEnumerable <string> counselor, IEnumerable <string> groupname) { if (AuthTokens[0] == "demo") { ViewBag.DemoNextStep = NextStep("!"); return(View()); } if (year != null && grade != null && counselor != null && groupname != null) { if (year.Count() == grade.Count() && year.Count() == counselor.Count() && year.Count() == groupname.Count()) { AdminAccountClient aac = new AdminAccountClient(); AccessCodeClient acc = new AccessCodeClient(); AdminAccount admin = aac.GetByPartitionAndRowKey("admin", AuthTokens[1].ToLower()); string school = admin.School; for (var i = 0; i < year.Count(); i++) { acc.AddNewItem(new AccessCode { RowKey = ShortGuidGenerator.NewGuid(), Code = PinCodeGenerator.NewPin(), Year = year.ElementAt(i), Grade = grade.ElementAt(i), Counselor = counselor.ElementAt(i), GroupName = groupname.ElementAt(i), School = school }); } ViewBag.CurrentYear = AccessCodeClient.CurrentGradYear(); return(View()); } } ViewBag.ErrorMessage = "error"; ViewBag.CurrentYear = AccessCodeClient.CurrentGradYear(); return(View()); }
/// <summary> /// 增 /// </summary> /// <param name="model"></param> /// <returns></returns> public JsonRsp Add(AdminAccount model) { JsonRsp json = CheckAccount(model.AccountName); if (!json.success) { json.retmsg = "该用户名已存在"; return(json); } if (string.IsNullOrEmpty(model.AccountPwd)) { model.AccountPwd = "888888"; } //salt string strSalt = Guid.NewGuid().ToString(); model.Salt = strSalt; model.AccountPwd = EncryptHelper.MD5Encoding(model.AccountPwd, strSalt); int returnvalue = Add <AdminAccount>(model); return(new JsonRsp { success = returnvalue > 0, code = returnvalue }); }
private PlantDexHttpResponse RunRequestedCommand(string command, List <Object> data) { PlantDexHttpResponse response = new PlantDexHttpResponse(); response.status = "FAIL"; response.message = "UNKNOWN COMMAND : " + command; switch (command) { case "InsertAdminAccount": { try { AdminAccount account = JsonConvert.DeserializeObject <AdminAccount>(data[0].ToString()); response = PlantDexHttpRequestManager.InsertAdminAccount(account); } catch (Exception ex) { response.status = "FAIL"; response.message = ex.Message + " - " + data[0]; } return(response); } default: { return(response); } } }
public bool ValidateUser(string login, string password) { AdminAccount ValidatedAccount = null; var accounts = context.AdminAccounts; foreach (var account in accounts) { if (account.Login == login) { using (var deriveBytes = new Rfc2898DeriveBytes(password, account.Salt)) { byte[] key = deriveBytes.GetBytes(20); // derive a 20-byte key if (!key.SequenceEqual(account.Key)) { return(false); } ValidatedAccount = account; } } } if (ValidatedAccount != null) { FormsAuthentication.SetAuthCookie(ValidatedAccount.Login, false); return(true); } return(false); }
public ActionResult Login(AdminAccount account, string returnUrl) { if (ModelState.IsValid) { if (this.isValid(account.username, account.pass)) { FormsAuthentication.SetAuthCookie(account.username, account.isRemember); if (!String.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl.Replace("%2f", "/"))); } else { return(RedirectToAction("Index", "AdminHome")); } } else { ModelState.AddModelError("", "Đăng nhập không thành công "); ModelState.AddModelError("", "Tên đăng nhập hoặc mật khẩu có thể không tồn tại !"); ModelState.AddModelError("", "Tài khoản của bạn có thể bị khóa hoặc không có quyền truy cập trang này !"); } } return(View(account)); }
public ActionResult Login(AdminAccount user) { conn.Open(); SqlCommand cmd = new SqlCommand("select Status, Username, Password FROM dbo.ADMIN WHERE Username = '******' and Password = '******';", conn); //int res = 0; SqlDataReader rd = cmd.ExecuteReader(); if (rd.Read()) { Session["Status"] = rd["Status"].ToString(); Session["Username"] = rd["Username"].ToString(); if (Session["Status"].ToString() == "admin1") { //Main Administration Section return(RedirectToAction("LoggedIn", "Admin")); } else if (Session["Status"].ToString() == "admin2") { //Sub Administration Section return(RedirectToAction("Index", "Home")); } conn.Close(); } else { ViewData["error"] = "Incorrect Username or Password"; return(View()); } return(View()); }
private async void btnDelete_Click(object sender, EventArgs e) { // Lay tai khoan admin dang duoc chon trong bang AdminAccount adminAccount = GetSelectedAdminAccount(); // Neu hien tai khong co tai khoan nao duoc chon thi hien thong bao if (adminAccount == null) { MessageBox.Show("You must choose an account to edit!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } // Neu co tai khoan dang duoc chon thi sua cot IsActive lai thanh False adminAccount.IsActive = false; // Gui len server de cap nhat lai cot IsActive trong CSDL AdminAccountWrapper adminAccountWrapper = new AdminAccountWrapper(); bool isSuccess = await adminAccountWrapper.Put(adminAccount.ID, adminAccount); // Kiem tra ket qua tra ve if (isSuccess) { // Neu ket qua la thanh cong, hien thong bao thanh cong MessageBox.Show("Account status was set to inactive!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); // Load lai bang LoadDataGridView(); } else { // Neu ket qua that bai, hien thong bao loi MessageBox.Show("An error has occurred!\n" + adminAccountWrapper.GetErrorMessage(), "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private AdminAccount GetSelectedAdminAccount() { // Neu khong co dong nao dang duoc chon thi tra ve null if (dgvAdmin.SelectedRows.Count != 1) { return(null); } // Neu co 1 dong dang duoc chon thi lay dong do ra DataGridViewRow row = dgvAdmin.SelectedRows[0]; // Lay du lieu trong dong do va tao ra mot AdminAccount moi AdminAccount adminAccount = new AdminAccount() { ID = Convert.ToInt32(row.Cells["ID"].Value), Username = row.Cells["Username"].Value.ToString(), Password = row.Cells["Password"].Value.ToString(), Name = row.Cells["Name"].Value.ToString(), Role = row.Cells["Role"].Value.ToString(), IsActive = Convert.ToBoolean(row.Cells["IsActive"].Value) }; // Tra AdminAccount vua tao ve return(adminAccount); }
public ActionResult SubmitSchool(FormCollection collection) { if (AuthTokens[0] == "demo") { ViewBag.DemoNextStep = NextStep("!"); return(View()); } string admin = AuthTokens[1]; AdminAccountClient aac = new AdminAccountClient(); AdminAccount adminAccount = aac.GetByPartitionAndRowKey("admin", admin); UserAccountClient uac = new UserAccountClient(); UserAccount user = uac.GetByPartitionAndRowKey(UserAccountClient.GetPartitionKeyForEmail(admin), admin); string rowkey = Regex.Replace(collection["schoolphone"], @"[^0-9]", ""); string phone = rowkey.Substring(0, 3) + "-" + rowkey.Substring(3, 3) + "-" + rowkey.Substring(6); PendingSchoolClient psc = new PendingSchoolClient(); psc.AddNewItem(new PendingSchool { Admin = admin, SchoolName = collection["schoolname"], Address = collection["schooladdress1"], City = collection["schoolcity"], State = collection["schoolstate"], ZipCode = collection["schoolzip"], OfficialID = collection["schoolid"], PhoneNumber = phone, RowKey = rowkey }); adminAccount.SchoolSelected = true; adminAccount.School = rowkey; adminAccount.RequestStatus = ""; aac.Update(adminAccount); EmailManager emailManager = new EmailManager(); string body = "<div>Admin name: " + user.FirstName + " " + user.LastName + "</div><div>Admin phone number and extension:" + adminAccount.PhoneNumber + " x " + adminAccount.PhoneExtension + "</div><div>Admin Email: " + adminAccount.RowKey + "</div>" + "<div>School name: " + collection["schoolname"] + "</div><div>School address" + collection["schooladdress1"] + " " + collection["schoolcity"] + " " + collection["schoolstate"] + " " + collection["schoolzip"] + "</div>" + "<div>School phone number: " + phone + "</div>"; emailManager.SendMail("*****@*****.**", "Admin", "*****@*****.**", "School request", body); return(RedirectToAction("SchoolSubmitted")); }
/// <summary> /// Arguement "password" should be hashed. /// </summary> /// <param name="username"></param> /// <param name="password"></param> public AdminValidation(string username, string password) : base(username, password) { //account exists if (isOldAccountValid) { //setting properties //existing account is admin if (account.IsAdmin) { isAccountAdmin = true; } else { isAccountAdmin = false; adminAccount = null; } //building error message if (!isAccountAdmin) { ErrorMessage += "Those details don't belong to an admin.\n"; } } else { isAccountAdmin = false; } }
public async Task <AdminAccount> GetAdminBySigninInfo(string signin) { AdminAccount adminAccount = null; SqlParameter parameter = new SqlParameter("signin", signin); try { var adminAccounts = await _db.AdminAccount.FromSqlRaw("sp_getAdminBySignInInfo @signin", parameter).ToListAsync(); if (adminAccounts.Count > 0) { adminAccount = new AdminAccount(); foreach (var admin in adminAccounts) { adminAccount = admin; break; } } } catch (Exception ex) { Console.WriteLine(ex); } return(adminAccount); }
public IHttpActionResult PostAdminAccount(AdminAccount adminAccount) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { db.AdminAccounts.Add(adminAccount); db.SaveChanges(); } catch (Exception ex) { if (IsDuplicateUsername(adminAccount.Username)) { return(Content(HttpStatusCode.Conflict, "Username already existed!")); } else { while (ex.InnerException != null) { ex = ex.InnerException; } return(Content(HttpStatusCode.InternalServerError, ex.Message)); } } return(CreatedAtRoute("DefaultApi", new { id = adminAccount.ID }, adminAccount)); }
public ActionResult RemoveUser(int id) { AdminAccount.DeleteUser(id); ViewBag.Success = "Brugeren er nu slettet"; return(this.Redirect(this.Request.UrlReferrer.PathAndQuery)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { AdminAccount.SetupAdminAccount(app); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } 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.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); }
private AdminAccount Mapper(IDataReader reader) { try { AdminAccount _AdminAccount = new AdminAccount(); if (reader[ID] != null && reader[ID] != DBNull.Value) { _AdminAccount.ID = Common.Conversion.ToLong(reader[ID]); } if (reader[USERNAME] != null && reader[USERNAME] != DBNull.Value) { _AdminAccount.UserName = Common.Conversion.ToString(reader[USERNAME]); } if (reader[PASSCODE] != null && reader[PASSCODE] != DBNull.Value) { _AdminAccount.PassCode = Common.Conversion.ToString(reader[PASSCODE]); } return(_AdminAccount); } catch (Exception exception) { throw exception; } }
/// <summary> /// 分配角色 /// </summary> /// <returns></returns> // GET: /Admin/Role/SetRole public ActionResult SetRole(int Id) { AdminAccount account = accountbll.GetModelById(Id); ViewBag.model = account; return(View()); }
/// <summary> /// save /// </summary> /// <param name="model"></param> /// <returns></returns> public JsonRsp SaveAccountRole(AdminAccount model, int[] itemIds) { AdminAccountRole emp = new AdminAccountRole(); emp.AccountID = model.ID; //删除原有的 OQL q = OQL.From(emp) .Delete() .Where(emp.AccountID) .END; EntityQuery <AdminAccountRole> .Instance.ExecuteOql(q); List <AdminAccountRole> list = new List <AdminAccountRole>(); foreach (int id in itemIds) { list.Add(new AdminAccountRole { AccountID = model.ID, RoleID = id, }); } int returnvalue = EntityQuery <AdminAccountRole> .Instance.Insert(list); return(new JsonRsp { success = returnvalue > 0, code = 0, returnvalue = returnvalue }); }
/// <summary> /// 获取管理员列表(全部) /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public JsonRsp <AccountViewModel> GetAllList() { JsonRsp <AccountViewModel> rsp = new JsonRsp <AccountViewModel>(); AdminAccount model = new AdminAccount(); OQL q = OQL.From(model) .Select() .OrderBy(model.ID, "asc") .END; List <AdminAccount> list = q.ToList <AdminAccount>();//使用OQL扩展 rsp.data = list.ConvertAll <AccountViewModel>(o => { return(new AccountViewModel() { ID = o.ID, AccountName = o.AccountName, TrueName = o.TrueName, Status = o.Status, LoginTime = o.LoginTime, LastLoginTime = o.LastLoginTime, LoginCount = o.LoginCount, CreateTime = o.CreateTIme, }); } ); rsp.success = true; rsp.code = 0; return(rsp); }
private async void btnLogin_Click(object sender, EventArgs e) { if (txtUsername.Text == "" || txtPassword.Text == "") { MessageBox.Show("Username and password must not be null", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (lstAdminAccount == null) { AdminAccountWrapper adminAccountWrapper = new AdminAccountWrapper(); lstAdminAccount = await adminAccountWrapper.List(); } string username = txtUsername.Text; string password = ARSUtilities.Md5Hash(txtPassword.Text); AdminAccount adminAccount = lstAdminAccount.Where(aa => aa.Username == username && aa.Password.ToLower() == password.ToLower()).SingleOrDefault(); if (adminAccount == null) { MessageBox.Show("Wrong username or password!", "Login failed", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } fMain.isLoggedIn = isLoggedIn = true; Close(); }
/// <summary> /// 登录 /// </summary> /// <param name="customerID"></param> /// <returns></returns> public JsonRsp Login(string accountName, string accountPwd) { JsonRsp json = new JsonRsp(); AdminAccount model = new AdminAccount(); model.AccountName = accountName; OQL q = OQL.From(model) .Select() .Where(model.AccountName) //以用户名和密码来验证登录 .END; model = q.ToEntity <AdminAccount>();//ToEntity,OQL扩展方法 if (model == null) { json.success = false; json.retmsg = "账号或密码不匹配"; } else { if (model.AccountPwd == EncryptHelper.MD5Encoding(accountPwd, model.Salt)) { json.success = true; json.code = 0; json.returnObj = model; } else { json.success = false; json.retmsg = "账号或密码不匹配"; } } return(json); }
/// <summary> /// 启用/禁用/删除 /// </summary> /// <param name="accountStatus"></param> /// <returns></returns> public JsonRsp SetStatus(int accountId, int accountStatus) { AdminAccount dbAccount = GetModelById(accountId); dbAccount.Status = accountStatus; return(Update(dbAccount)); }
public ActionResult DoiMatKhau(int id) { AdminDetail admin = new AdminDetail(); AdminAccount ac = admin.Tim(id); ViewBag.ac = ac; return(View()); }
public void RegisterUser(AdminAccount model) { using (HFContext context = new HFContext()) { context.AdminAccounts.Add(model); context.SaveChanges(); } }
/// <summary> /// 删 /// </summary> /// <param name="model"></param> /// <returns></returns> public JsonRsp Remove(AdminAccount model) { bool success = Delete <AdminAccount>(model); return(new JsonRsp { success = success }); }