public async Task <IActionResult> PostChangePassword([FromBody] ChangePassword changepsw) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var existAccount = _context.Account.SingleOrDefault(a => a.Id == changepsw.OwnerId); if (existAccount != null) { if (existAccount.Password == PasswordHandle.GetInstance().EncryptPassword(changepsw.OldPassword, existAccount.Salt)) { existAccount.Password = PasswordHandle.GetInstance().EncryptPassword(changepsw.NewPassword, existAccount.Salt); await _context.SaveChangesAsync(); return(new JsonResult("Đổi mật khẩu thành công!")); } return(BadRequest("Mật khẩu cũ không chính xác!")); } else { return(new JsonResult("Tài khoản không tồn tại!")); } }
public async Task <IActionResult> PostMember([FromBody] MemberLogin member) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Member existMember = _context.Member.FirstOrDefault(m => m.Email == member.Email); if (existMember == null) { return(NotFound()); } if (PasswordHandle.GetInstance().EncryPassword(member.Password, existMember.Salt) == null) { return(StatusCode(403, new { status = 403, message = "Invalid" })); } ShCredential credential = ShCredential.GenerateCredential(existMember.Id, CredentialScope.Basic); _context.ShCredentials.Add(credential); _context.SaveChanges(); return(new JsonResult(credential)); }
public async Task <IActionResult> StudentLogin(LoginInformation loginInformation) { // find 1 account with matching username in Account var ac = await _context.Account.SingleOrDefaultAsync(a => a.Username == loginInformation.Username); if (ac != null) { var isCorrectClient = ac.Id.StartsWith("STU"); if (isCorrectClient) { // check matching password if (ac.Password == PasswordHandle.GetInstance().EncryptPassword(loginInformation.Password, ac.Salt)) { // check if account is deactivated if (ac.Status != AccountStatus.Deactive) { // check if account is logged in elsewhere var cr = await _context.Credential.SingleOrDefaultAsync(c => c.OwnerId == ac.Id); var accessToken = TokenHandle.GetInstance().GenerateToken(); if (cr != null) // if account has logged in { cr.AccessToken = accessToken; // update token _context.Credential.Update(cr); await _context.SaveChangesAsync(); return(Ok(accessToken)); } // create new credential with AccountId var firstCredential = new Credential { OwnerId = ac.Id, AccessToken = accessToken }; // save token _context.Credential.Add(firstCredential); await _context.SaveChangesAsync(); return(Ok(accessToken)); } return(Forbid("Your account is deactivated. Contact managers for more information.")); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("UserName or Password is incorrect", (int)HttpStatusCode.Forbidden))); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("Client is Wrong", (int)HttpStatusCode.Forbidden))); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("UserName or Password is incorrect", (int)HttpStatusCode.Forbidden))); }
public async Task <IActionResult> PutAccount([FromRoute] string id, [FromBody] Account account) { _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != account.Id) { return(BadRequest("ID is not correct")); } if (await _context.Account.SingleOrDefaultAsync(a => a.Id == account.Id) != null) // Kiem tra account update co ton tai khong { var currentAccount = await _context.Account.SingleOrDefaultAsync(a => a.Id == account.Id); string tokenHeader = Request.Headers["Authorization"]; var token = tokenHeader.Replace("Basic ", ""); var tokenUser = await _context.Credential.SingleOrDefaultAsync(c => c.AccessToken == token); if (tokenUser.OwnerId == currentAccount.Id || (await _context.AccountRoles.SingleOrDefaultAsync(ar => ar.AccountId == tokenUser.OwnerId)).RoleId < (await _context.AccountRoles.SingleOrDefaultAsync(ar => ar.AccountId == currentAccount.Id)).RoleId || tokenUser.OwnerId == "ADMIN" ) { if (account.Password == null) { account.Password = currentAccount.Password; account.Salt = currentAccount.Salt; } else { if (PasswordHandle.GetInstance().EncryptPassword(account.Password, currentAccount.Salt) == currentAccount.Password) //Kiểm tra mật khẩu có trùng với mật khẩu cũ không, nếu trùng thì trả về lỗi { return(BadRequest(new ResponseError("New password do not same old password", 400))); } account.Salt = PasswordHandle.GetInstance().GenerateSalt(); account.Password = PasswordHandle.GetInstance().EncryptPassword(account.Password, account.Salt); } account.UpdatedAt = DateTime.Now; _context.Entry(account).State = EntityState.Modified; _context.Entry(account.GeneralInformation).State = EntityState.Modified; await _context.SaveChangesAsync(); return(Ok(_context.Account.Include(a => a.GeneralInformation).SingleOrDefault(a => a.Id == account.Id))); } } return(BadRequest(account.Id)); }
public async Task <IActionResult> Login([Bind("Id,Email,Password")] Login login) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var existAccount = _context.Account.SingleOrDefault(a => a.Email == login.Email); if (existAccount != null) { string[] listTypeRole = { "A", "M" }; var email = ""; if (existAccount.RollNumber.Any()) { email = existAccount.RollNumber[0].ToString(); } if (!listTypeRole.Contains(email.ToUpper())) { HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden; return(new JsonResult("Bạn không có quyền truy cập!")); } else if (existAccount.Password == PasswordHandle.GetInstance().EncryptPassword(login.Password, existAccount.Salt)) { HttpContext.Session.SetString("loggedUserEmail", existAccount.Email); HttpContext.Session.SetString("loggedUserId", existAccount.Id.ToString()); var existCredential = await _context.Credential.SingleOrDefaultAsync(c => c.OwnerId == existAccount.Id); if (existCredential != null) { var accessToken = PasswordGenerator.Generate(length: 40, allowed: Sets.Alphanumerics); existCredential.AccessToken = accessToken; HttpContext.Session.SetString("loggedUserToken", accessToken); await _context.SaveChangesAsync(); } else { var credential = new Credential(existAccount.Id) { AccessToken = PasswordGenerator.Generate(length: 40, allowed: Sets.Alphanumerics) }; HttpContext.Session.SetString("loggedUserToken", credential.AccessToken); _context.Credential.Add(credential); await _context.SaveChangesAsync(); } return(Redirect("/")); } return(BadRequest("Mật khẩu không chính xác!")); } return(BadRequest("Email hoặc mật khẩu không chính xác!")); }
public async Task <IActionResult> Create([Bind("Id,Email,Password,Salt,CreatedAt,UpdatedAd,Status")] Account account) { if (ModelState.IsValid) { account.Salt = PasswordHandle.GetInstance().GenerateSalt(); account.Password = PasswordHandle.GetInstance() .EncryptPassword(account.Password, account.Salt); _context.Account.Add(account); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(account)); }
public async Task <IActionResult> PostMember([FromBody] Member member) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } member.Salt = PasswordHandle.GetInstance().GenerateSalt(); member.Password = PasswordHandle.GetInstance().EncryPassword(member.Password, member.Salt); _context.Member.Add(member); await _context.SaveChangesAsync(); return(CreatedAtAction("GetMember", new { id = member.Id }, member)); }
public async Task <IActionResult> PostLogin([FromBody] Login login) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var existAccount = _context.Account.SingleOrDefault(a => a.Email == login.Email); if (existAccount != null) { if (existAccount.Password == PasswordHandle.GetInstance().EncryptPassword(login.Password, existAccount.Salt)) { var existCredential = await _context.Credential.SingleOrDefaultAsync(c => c.OwnerId == existAccount.Id); if (existCredential != null) { var accessToken = PasswordGenerator.Generate(length: 40, allowed: Sets.Alphanumerics); existCredential.AccessToken = accessToken; await _context.SaveChangesAsync(); return(Ok(existCredential)); } else { var credential = new Credential(existAccount.Id) { AccessToken = PasswordGenerator.Generate(length: 40, allowed: Sets.Alphanumerics) }; _context.Credential.Add(credential); await _context.SaveChangesAsync(); return(Ok(credential)); } } return(BadRequest("Mật khẩu không chính xác!")); } return(BadRequest("Email hoặc mật khẩu không chính xác!")); }
public IActionResult Authentication(LoginInformation loginInformation) { if (!ModelState.IsValid) { return(View("Login", loginInformation)); } Account existAccount = _context.Account.FirstOrDefault(m => m.Email == loginInformation.Email); if (existAccount == null) { return(View("Login", loginInformation)); } if (PasswordHandle.GetInstance().EncryptPassword(loginInformation.Password, existAccount.Salt) != existAccount.Password) { return(View("Login", loginInformation)); } Credential credential = Credential.GenerateCredential(existAccount.Id, new List <CredentialScope>() { CredentialScope.Basic }); _context.Credential.Add(credential); _context.SaveChanges(); Response.Cookies.Append( OAUTH2_COOKIE, credential.AccessToken, new CookieOptions() { Path = "/" } ); return(Redirect(loginInformation.RedirectUrl)); }
public static void Initialize(this BackendContext context) { // Seeder for role if (!context.Role.Any()) { context.AddRange( new Role { Name = "Admin", Description = "Set role for Admin User" }, new Role { Name = "Manage", Description = "Set role for Manage User" }, new Role { Name = "Student", Description = "Set role for Student User" }); context.SaveChanges(); } // Seeder for account: 1 admin, 2 managers, 2 students if (!context.Account.Any()) { var salt1 = PasswordHandle.GetInstance().GenerateSalt(); var salt2 = PasswordHandle.GetInstance().GenerateSalt(); var salt3 = PasswordHandle.GetInstance().GenerateSalt(); var salt4 = PasswordHandle.GetInstance().GenerateSalt(); var salt5 = PasswordHandle.GetInstance().GenerateSalt(); context.AddRange( new Account { Id = "ADMIN", Username = "******", Salt = salt1, Password = PasswordHandle.GetInstance().EncryptPassword("Amin@123", salt1), Email = "*****@*****.**", }, new Account { Id = "MNG0001", Username = "******", Salt = salt2, Password = PasswordHandle.GetInstance().EncryptPassword("A123@a123", salt2), Email = "*****@*****.**", }, new Account { Id = "MNG0002", Username = "******", Salt = salt3, Password = PasswordHandle.GetInstance().EncryptPassword("A123@a123", salt3), Email = "*****@*****.**", }, new Account { Id = "STU0001", Username = "******", Salt = salt4, Password = PasswordHandle.GetInstance().EncryptPassword("A123@a123", salt4), Email = "*****@*****.**", }, new Account { Id = "STU0002", Username = "******", Salt = salt5, Password = PasswordHandle.GetInstance().EncryptPassword("A123@a123", salt5), Email = "*****@*****.**", } ); context.SaveChanges(); } // Seeder for general information if (!context.GeneralInformation.Any()) { var salt = PasswordHandle.GetInstance().GenerateSalt(); context.AddRange( new GeneralInformation { AccountId = "ADMIN", FirstName = "ADMIN", LastName = "ADMIN", Phone = "01234567890" }, new GeneralInformation { AccountId = "MNG0001", FirstName = "Hung", LastName = "Dao", Phone = "013237416", }, new GeneralInformation { AccountId = "MNG0002", FirstName = "Luyen", LastName = "Dao", Phone = "013257416", }, new GeneralInformation { AccountId = "STU0001", FirstName = "Thao", LastName = "Nguyen", Phone = "013257983", }, new GeneralInformation { AccountId = "STU0002", FirstName = "Anh", LastName = "Nguyen", Phone = "0130387983", } ); context.SaveChanges(); } // Seeder for account-role if (!context.AccountRoles.Any()) { context.AddRange( new AccountRole { AccountId = "ADMIN", RoleId = 1, }, new AccountRole { AccountId = "MNG0001", RoleId = 2, }, new AccountRole { AccountId = "MNG0002", RoleId = 2, }, new AccountRole() { AccountId = "STU0002", RoleId = 3, }, new AccountRole() { AccountId = "STU0001", RoleId = 3, } ); context.SaveChanges(); } // Seeder for subject: 7 subjects if (!context.Subject.Any()) { context.Subject.AddRange( new Subject { Id = "WFP", Name = "Windows Forms Programming", Description = "Working with Windows Forms" }, new Subject { Id = "WAD", Name = "Web Application Development", Description = "Develop web application" }, new Subject { Id = "EAP", Name = "Enterprise Application Programming", Description = "Develop enterprise application" }, new Subject { Id = "WCC", Name = "Working with Cloud Computing", Description = "Cloud Computing" }, new Subject { Id = "MCC", Name = "Mobile & Cloud Computing", Description = "Working with Mobile & Cloud Computing" }, new Subject { Id = "IEH", Name = "Introduction to Ethical hacking", Description = "Ethical hacking introduction" }, new Subject { Id = "ICC", Name = "Introduction to Cloud Computing", Description = "Cloud computing introduction" } ); context.SaveChanges(); } // Seeder for class: 3 classes if (!context.Clazz.Any()) { context.Clazz.AddRange( new Clazz { Id = "T1707A", StartDate = DateTime.Now, Session = ClazzSession.Afternoon, Status = ClazzStatus.Active, CurrentSubjectId = "WAD" }, new Clazz { Id = "T1707M", StartDate = DateTime.Now, Session = ClazzSession.Morning, Status = ClazzStatus.Active, CurrentSubjectId = "WFP" }, new Clazz { Id = "T1707E", StartDate = DateTime.Now, Session = ClazzSession.Evening, Status = ClazzStatus.Active, CurrentSubjectId = "EAP" } ); context.SaveChanges(); } // Seeder for class-account: 3 if (!context.ClazzAccount.Any()) { context.ClazzAccount.AddRange( new ClazzAccount { ClazzId = "T1707A", AccountId = "STU0001" }, new ClazzAccount { ClazzId = "T1707M", AccountId = "STU0001" }, new ClazzAccount { ClazzId = "T1707E", AccountId = "STU0002" } ); context.SaveChanges(); } // Seeder for class-subject: 5 if (!context.ClazzSubject.Any()) { context.ClazzSubject.AddRange( new ClazzSubject { ClazzId = "T1707A", SubjectId = "WFP" }, new ClazzSubject { ClazzId = "T1707A", SubjectId = "WAD" }, new ClazzSubject { ClazzId = "T1707M", SubjectId = "WFP" }, new ClazzSubject { ClazzId = "T1707E", SubjectId = "EAP" }, new ClazzSubject { ClazzId = "T1707E", SubjectId = "WAD" } ); context.SaveChanges(); } // Seeder for mark (2 students) if (!context.Mark.Any()) { context.Mark.AddRange( new Mark { AccountId = "STU0001", SubjectId = "WFP", Value = 10, MarkType = MarkType.Theory }, new Mark { AccountId = "STU0002", SubjectId = "WFP", Value = 8, MarkType = MarkType.Theory }, new Mark { AccountId = "STU0001", SubjectId = "WAD", Value = 5, MarkType = MarkType.Theory }, new Mark { AccountId = "STU0001", SubjectId = "WFP", Value = 9, MarkType = MarkType.Assignment }, new Mark { AccountId = "STU0002", SubjectId = "WFP", Value = 7, MarkType = MarkType.Assignment }, new Mark { AccountId = "STU0001", SubjectId = "WFP", Value = 12, MarkType = MarkType.Practice }, new Mark { AccountId = "STU0002", SubjectId = "WFP", Value = 5, MarkType = MarkType.Practice } ); context.SaveChanges(); } }
public async Task <IActionResult> Create([Bind("Id,FirstName,LastName,BirthDay,Phone")] AccountInfomation accountInfomation, int[] classIds, int roleId) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var Rnb = ""; switch (roleId) { case 1: Rnb = "A"; break; case 2: Rnb = "M"; break; case 3: Rnb = "D"; break; default: return(BadRequest()); } //Generate RollNumber var count = await _context.Account.CountAsync(a => a.RollNumber.Contains(Rnb)) + 1; string rollNumber; if (count < 10) { rollNumber = "0000" + count; } else if (count < 100) { rollNumber = "000" + count; } else if (count < 1000) { rollNumber = "00" + count; } else if (count < 10000) { rollNumber = "0" + count; } else { rollNumber = count.ToString(); } var rnber = (Rnb + rollNumber).ToLower(); // Generate Email var str = accountInfomation.FirstName.Split(" "); string email = accountInfomation.LastName; foreach (var item in str) { if (item.Any()) { email += item[0]; } } email = email.ToLower(); var emailGenerate = RemoveUTF8.RemoveSign4VietnameseString(email + rnber + "@siingroup.com").ToLower(); var passwordGenerate = RemoveUTF8.RemoveSign4VietnameseString(email + rnber); //Create new account Account account = new Account { RollNumber = rnber, Email = emailGenerate, Salt = PasswordHandle.GetInstance().GenerateSalt() }; account.Password = PasswordHandle.GetInstance().EncryptPassword(passwordGenerate, account.Salt); _context.Account.Add(account); //Create thông tin đăng nhập để trả về response Login login = new Login { Email = emailGenerate, Password = passwordGenerate }; //Check uniqe by phone if (AccountExistsByPhone(accountInfomation.Phone)) { return(Conflict("Tài khoản đã tồn tại trên hệ thống, vui lòng kiểm tra lại!")); } else { //Save account await _context.SaveChangesAsync(); //Get ra account.Id để gán cho FK ownerId bên accountinfomation accountInfomation.OwnerId = account.Id; _context.AccountInfomation.Add(accountInfomation); await _context.SaveChangesAsync(); AccountLogsDefault log = new AccountLogsDefault { Title = "Đã tạo tài khoản với email " + login.Email + "!" }; _context.Default.Add(log); AccountLogs al = new AccountLogs { OwnerId = account.Id, CreatedBy = accountInfomation.FirstName + " " + accountInfomation.LastName, Default = log }; _context.Log.Add(al); await _context.SaveChangesAsync(); foreach (var item in classIds) { Classes classes = new Classes { OwnerId = account.Id, ClassId = item }; _context.Classes.Add(classes); AccountLogsDefault logs = new AccountLogsDefault(); var classAccount = _context.Class.SingleOrDefault(a => a.Id == classes.ClassId); logs.Title = accountInfomation.FirstName + " " + accountInfomation.LastName + " đã xếp bạn vào lớp " + classAccount.Name; _context.Default.Add(logs); AccountLogs als = new AccountLogs { OwnerId = account.Id, CreatedBy = accountInfomation.FirstName + " " + accountInfomation.LastName, Default = logs }; _context.Log.Add(als); } await _context.SaveChangesAsync(); } return(Created("", login)); }