public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (var db = new OnlineMusicEntities()) { var user = (from u in db.Users where u.Username.ToLower() == context.UserName.ToLower() select u).FirstOrDefault(); MemoryCacher cache = new MemoryCacher(); string cachePassword = string.Empty; if (user != null && cache.Get(user.Username) != null) { cachePassword = (string)cache.Get(user.Username); } if (user != null && (HashingPassword.ValidatePassword(context.Password, user.Password) || (!String.IsNullOrEmpty(cachePassword) && HashingPassword.ValidatePassword(context.Password, cachePassword)))) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.Id.ToString())); if (user.RoleId == (int)RoleManager.Administrator) { identity.AddClaim(new Claim(ClaimTypes.Role, "Administrator")); identity.AddClaim(new Claim(ClaimTypes.Role, "Admin")); identity.AddClaim(new Claim(ClaimTypes.Role, "User")); } else if (user.RoleId == (int)RoleManager.Admin) { identity.AddClaim(new Claim(ClaimTypes.Role, "Admin")); identity.AddClaim(new Claim(ClaimTypes.Role, "User")); } else if (user.RoleId == (int)RoleManager.VIP) { identity.AddClaim(new Claim(ClaimTypes.Role, "VIP")); identity.AddClaim(new Claim(ClaimTypes.Role, "User")); } else if (user.RoleId == (int)RoleManager.User) { identity.AddClaim(new Claim(ClaimTypes.Role, "User")); } else { return; } context.Validated(identity); } else { context.SetError("Invalid Grant", "Provided username and password is incorrect"); return; } } }
private async Task <IEnumerable <User> > ValidateCache() { IEnumerable <User> users = cache.Get(nameof(User)); if (users == null) { try { users = await dataService.GetUsers(); cache.Add(nameof(User), users); } catch (Exception) { users = new List <User> { new User { Id = 0, FirstName = "No", LastName = "Data" } }; } } return(users); }
public HttpResponseMessage Login([FromBody] UserLoginModel userLogin) { try { using (var db = new OnlineMusicEntities()) { bool success = false; var user = (from u in db.Users where u.Username.ToLower() == userLogin.Username.ToLower() select u).FirstOrDefault(); if (user != null) { // Prevent if user is blocked if (user.Blocked) { return(Request.CreateResponse(HttpStatusCode.Forbidden)); } MemoryCacher cache = new MemoryCacher(); string cachePassword = cache.Get(user.Username) != null ? (string)cache.Get(user.Username) : String.Empty; success = HashingPassword.ValidatePassword(userLogin.Password, user.Password); if (!success) { success = !String.IsNullOrEmpty(cachePassword) && HashingPassword.ValidatePassword(userLogin.Password, cachePassword); if (success) { Notification notification = new Notification() { Title = "Đăng nhập với mật khẩu tạm thời", Message = "Bạn vừa đăng nhập bằng mật khẩu tạm thời của mình vào " + DateTime.Now.ToString() + "\nNếu đây không phải là bạn, khuyên cáo bạn nên đổi lại mật khẩu của mình", UserId = user.Id, IsMark = false, CreatedAt = DateTime.Now, Action = NotificationAction.LOGIN_TEMPORARILY }; db.Notifications.Add(notification); db.SaveChanges(); } } } if (success) { return(Request.CreateResponse(HttpStatusCode.OK, new UserModel { User = user })); } else { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public void Should_cache_and_get() { MemoryCacher cacher = new MemoryCacher(); cacher.AddOrUpdate("mykey", cacher); var cached = cacher.Get <MemoryCacher>("mykey"); Assert.IsNotNull(cached); Assert.AreSame(cached, cacher); }
public HttpResponseMessage ChangePassword([FromUri] int id, PasswordModel passwordModel) { var identity = (ClaimsIdentity)User.Identity; if (identity.Name != id.ToString()) { return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Token")); } using (var db = new OnlineMusicEntities()) { try { var user = (from u in db.Users where u.Id == id select u).FirstOrDefault(); if (user == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Tài khoản với id={id} không tồn tại")); } else { MemoryCacher cache = new MemoryCacher(); string cachePassword = cache.Get(user.Username) != null ? (string)cache.Get(user.Username) : String.Empty; bool isValid = HashingPassword.ValidatePassword(passwordModel.OldPassword, user.Password); if (!isValid) { // Try check cache password isValid = !String.IsNullOrEmpty(cachePassword) && HashingPassword.ValidatePassword(passwordModel.OldPassword, cachePassword); } if (!isValid) { return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Mật khẩu cũ không đúng")); } else { user.Password = HashingPassword.HashPassword(passwordModel.NewPassword); cache.Delete(user.Username); db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK)); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } } }
public HttpResponseMessage RecoveryPassword([FromBody] UserModel user) { try { using (var db = new OnlineMusicEntities()) { var userData = (from u in db.Users where u.Username.ToLower() == user.Username.ToLower() && u.Email.ToLower() == user.Email.ToLower() select u).FirstOrDefault(); if (userData == null) { return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Email sử dụng không trùng khớp với tài khoản")); } MemoryCacher cache = new MemoryCacher(); if (cache.Get(userData.Username) == null) { // Recovery password for user var rand = new Random(); byte[] randomBytes = Encoding.UTF8.GetBytes(rand.Next(100000, 999999).ToString()); string newPassword = Convert.ToBase64String(randomBytes); string subject = "Recovery password in Musikai"; string htmlBody = String.Format(@"<html><body> <h1>Hello, {0}</h1> <p style=""font-size: 30px"">Your temporary password is <em>{1}</em></p> <p style=""font-size: 27px"">The password is temporary and will expire within 3 days</p> <p style=""font-size: 25px""><strong>We recommend you change your own password after you login</strong></p> </body></html>", userData.Username, newPassword); if (PostEmail.Send(userData.Email, subject, htmlBody)) { newPassword = Convert.ToBase64String(Encoding.UTF8.GetBytes(newPassword)); string encryptedPassword = HashingPassword.HashPassword(newPassword); cache.Add(userData.Username, encryptedPassword, DateTimeOffset.Now.AddDays(3)); Notification notification = new Notification() { Title = "Phục hồi mật khẩu", Message = "Mật khẩu tạm thời của bạn đã được gửi tới email. Sau khi đăng nhập khuyên cáo bạn nên thay đổi mật khẩu của mình", UserId = userData.Id, IsMark = false, CreatedAt = DateTime.Now, Action = NotificationAction.RECOVERY_PASSWORD }; db.Notifications.Add(notification); db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, "Mật khẩu khôi phục đã được gửi tới email " + userData.Email)); } else { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } } else { return(Request.CreateResponse(HttpStatusCode.OK, "Mật khẩu phục hồi đã gửi tới email")); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.StackTrace)); } }