public static ApplicationUserLogin CreateUserLogin(string authToken, string authVerifier) { var oauth = new Core.Helpers.OAuth.Manager(); oauth["consumer_key"] = TwitterApiKey; oauth["consumer_secret"] = TwitterApiSecret; oauth["token"] = authToken; oauth.AcquireAccessToken("https://api.twitter.com/oauth/access_token", "POST", authVerifier); var twitterDto = new TwitterDto { OAuthToken = oauth["token"], OAuthTokenSecret = oauth["token_secret"], Username = oauth["username"], UserId = oauth["userid"] }; var userLogin = new ApplicationUserLogin { Provider = ProviderName, ProviderUserId = twitterDto.UserId, ProviderUsername = twitterDto.Username }; return(userLogin); }
public async Task <ActionResult <ApplicationUser> > Login(ApplicationUserLogin applicationUserLogin) { var applicationUserIdentity = await _userManager.FindByNameAsync(applicationUserLogin.Username); if (applicationUserIdentity != null) { var result = await _signInManager.CheckPasswordSignInAsync( applicationUserIdentity, applicationUserLogin.Password, false); if (result.Succeeded) { ApplicationUser applicationUser = new ApplicationUser { ApplicationUserId = applicationUserIdentity.ApplicationUserId, Username = applicationUserIdentity.Username, Email = applicationUserIdentity.Email, Fullname = applicationUserIdentity.Fullname, Token = _tokenService.CreateToken(applicationUserIdentity) }; return(Ok(applicationUser)); } } return(BadRequest("Invalid login attempt.")); }
public void RemoveUserLogin(ApplicationUser user, ApplicationUserLogin userLogin) { if (user.Logins.Any(f => f.Provider == userLogin.Provider && f.ProviderKey == userLogin.ProviderKey)) { user.Logins = user.Logins.Where(f => !(f.Provider == userLogin.Provider && f.ProviderKey == userLogin.ProviderKey)).ToList(); UpdateUser(user); } }
public void AddUserLogin(ApplicationUser user, ApplicationUserLogin userLogin) { var logins = user.Logins.ToList(); if (!logins.Any(f => f.Provider == userLogin.ProviderKey && f.ProviderKey == userLogin.ProviderKey)) { logins.Add(userLogin); user.Logins = logins; UpdateUser(user); } }
public ApplicationUser FindUserByLogin(ApplicationUserLogin userLogin) { if (userLogin == null) { throw new ArgumentNullException("userLogin"); } var loginProvider = userLogin.Provider; var providerKey = userLogin.ProviderKey; return(_users.FirstOrDefault(u => u.Logins != null && u.Logins.Any(l => StringEquals(l.Provider, loginProvider) && StringEquals(l.ProviderKey, providerKey)))); }
public CreateExternalUserResult CreateExternalUser(ApplicationUserLogin userLogin) { if (string.IsNullOrEmpty(userLogin.ProviderUserId) || string.IsNullOrEmpty(userLogin.ProviderUsername)) { throw HttpResponseExceptionHelper.Create($"{userLogin.Provider} account login failed", HttpStatusCode.BadRequest); } var result = new CreateExternalUserResult(); // Check if the user login is already in use var existingUserLogin = this.DbContext.UserLogins .FirstOrDefault(x => x.Provider == userLogin.Provider && x.ProviderUserId == userLogin.ProviderUserId); // User already exists if (existingUserLogin != null) { result.User = this.GetUserById(existingUserLogin.UserId); result.UserCreated = false; return(result); } // Take only the first part if email var username = userLogin.ProviderUsername.Split('@').First(); // If username is already in use, tweak it until it's available while (this.DbContext.Users.FirstOrDefault(x => x.Username == username) != null) { username += new Random().Next(0, 9); } userLogin.UserId = ApplicationUserManager.GetUserHash(userLogin.ProviderUsername); var newUser = new ApplicationUser { Username = username, Id = userLogin.UserId, UserLogins = new List <ApplicationUserLogin> { userLogin } }; this.DbContext.Users.Add(newUser); this.DbContext.SaveChanges(); result.User = newUser; result.UserCreated = true; AzureBlobStorageHelper.UploadDefaultAvatar(newUser.Id); return(result); }
public async void RegisterAndLoginByUserNamePassword() { string userid = string.Empty, username = string.Empty, email = string.Empty, userpassword = string.Empty; //1. 创建一个用户 ApplicationUser user = (await UserManager.CreateUserAsync(new ApplicationUser() { Email = email, //Email,必须,如果没有,则生成一个随机值或者组合一个有意义的值 UserName = username, //用户名,必须,如果没有,则生成一个随机值或者组合一个有意义的值 Id = userid, //如果自行指定ID,则会根据这个ID来生成用户,但需要调用方保证ID不冲突,否则系统自动生成 })).Data; //2. (只使用微信登录可掠过这一步)未设置密码的用户设置用户密码,必须把UserId带过来 await UserManager.ResetPasswordAsync(user.Id, userpassword); //3. (微信登录)添加一个LoginType ApplicationUserLogin userLogin = (await UserManager.AddUserLoginAsync(new ApplicationUserLogin() { LoginProvider = "微信", //设置一个唯一的常量 ProviderDisplayName = "微信", //展示用 ProviderKey = "${OPEN_ID}", //把微信OpenID写上 UserId = user.Id, //用户ID //如果自行指定ID,则会根据这个ID来生成用户,但需要调用方保证ID不冲突,否则系统自动生成 })).Data; //4. 添加用户到某个角色 ApplicationUserRole userRole = (await UserManager.AddUserRoleAsync(userid, "患者")).Data; //或者new一个ApplicationUserRole await UserManager.AddUserRoleAsync(userRole); //批量方法 await UserManager.AddUserRolesAsync(new ApplicationUserRole[] { userRole }); //5. (非外部来源)登录,随便选一个 LoginResponse loginResponse = await SignInManager.LoginByEmailAsync(email, userpassword); loginResponse = await SignInManager.LoginByUserIdAsync(userid, userpassword); loginResponse = await SignInManager.LoginByUserNameAsync(username, userpassword); //6. (外部来源:微信)用户登录 userLogin = (await UserManager.GetLoginByUserIdLoginTypeAsync(userid, "微信", "${OPEN_ID}")).Data; loginResponse = await SignInManager.ExternalLoginAsync(userLogin.LoginProvider, userLogin.ProviderKey); //7. 外部登录,去除绑定 await UserManager.RemoveUserLoginAsync(loginResponse.AccessToken, userLogin); //8. 删除角色 await UserManager.RemoveUserRoleAsync(loginResponse.AccessToken, userRole); }
public static ApplicationUserLogin CreateUserLogin(string accessToken) { var resp = HttpRequestHelper.GetAsync($"https://www.googleapis.com/plus/v1/people/me?fields=id%2Cemails%2Fvalue&access_token={accessToken}").Result; var json = resp.Content.ReadAsStringAsync().Result; var googleDto = JsonConvert.DeserializeObject <GoogleDto>(json); var userLogin = new ApplicationUserLogin { Provider = ProviderName, ProviderUserId = googleDto.Id, ProviderUsername = googleDto.Emails.FirstOrDefault()?.Value }; return(userLogin); }
public static ApplicationUserLogin CreateUserLogin(string accessToken) { var resp = HttpRequestHelper.GetAsync($"https://graph.facebook.com/v2.8/me?access_token={accessToken}&fields=id,email").Result; var json = resp.Content.ReadAsStringAsync().Result; var facebookDto = JsonConvert.DeserializeObject <FacebookDto>(json); var userLogin = new ApplicationUserLogin { Provider = ProviderName, ProviderUserId = facebookDto.Id, ProviderUsername = facebookDto.Email }; return(userLogin); }
/// <summary> /// 添加一个用户的账号关联登录信息。 /// 例如微信:userLogin.LoginProvider = '微信';userLogin.ProviderKey = ${OpenID} /// </summary> /// <param name="userLogin"></param> /// <returns></returns> public async Task <UserLoginResponseResult> AddUserLoginAsync(ApplicationUserLogin userLogin) { try { JObject response = await this.HttpPostAsync("api/userlogins/adduserlogin", JObject.FromObject(userLogin)); if (response != null) { return(JsonConvert.DeserializeObject <UserLoginResponseResult>(response.ToString())); } return(null); } catch (Exception ex) { throw new AuthException("UserManager.AddUserLoginAsync exception", ex); } }
public void RemoveUserLogin(ApplicationUser user, ApplicationUserLogin userLogin) { if (user == null) { throw new ArgumentNullException("user"); } if (userLogin == null) { throw new ArgumentNullException("userLogin"); } if (string.IsNullOrWhiteSpace(userLogin.Provider)) { throw new ArgumentException(@"Login provider cannot be null or whitespace."); } if (string.IsNullOrWhiteSpace(userLogin.ProviderKey)) { throw new ArgumentException(@"Provider key cannot be null or whitespace."); } // Поиск указанного пользователя var userEntry = FindUserById(user.Id); if (userEntry == null) { throw new ArgumentException(string.Format("User '{0}' does not exist.", user.Id)); } // Обновление записи хранилища пользователей if (userEntry.Logins == null) { userEntry.Logins = new List <ApplicationUserLogin>(); } userEntry.Logins = userEntry.Logins.Where(l => !StringEquals(l.Provider, userLogin.Provider) || !StringEquals(l.ProviderKey, userLogin.ProviderKey)).ToList(); // Обновление сведений пользователя UpdateInfo(user, userEntry); }
/// <summary> /// 去除一个用户的账号关联信息 /// </summary> /// <param name="userLogin"></param> public async Task <ActionResponseResult> RemoveUserLoginAsync(string token, ApplicationUserLogin userLogin) { try { JObject response = await this.TokenHttpPostAsync(token, "api/userlogins/removeuserlogin", JObject.FromObject(userLogin)); if (response != null) { return(JsonConvert.DeserializeObject <ActionResponseResult>( response.ToString())); } return(null); } catch (Exception ex) { throw new AuthException("UserManager.RemoveUserLoginAsync exception", ex); } }
public void ApplicationUserLogin_PublicProperties() { var testDate = DateTime.Today; var user = new ApplicationUser { Id = "123" }; var obj = new ApplicationUserLogin { CreatedAt = testDate, LastModifiedAt = testDate, CreatedBy = user, CreatedBy_Id = "123", LastModifiedBy = user, LastModifiedBy_Id = "123" }; Assert.AreEqual(testDate, obj.CreatedAt); Assert.AreEqual(testDate, obj.LastModifiedAt); Assert.AreEqual(user.Id, obj.CreatedBy_Id); Assert.AreEqual(user.Id, obj.LastModifiedBy_Id); }
public async Task <UserLoginResponseResult> AddUserLogin([FromBody] ApplicationUserLogin userLogin) { if (userLogin != null && !string.IsNullOrEmpty(userLogin.UserId)) { var user = await _userManager.FindByIdAsync(userLogin.UserId); if (user != null) { var result = await this._userManager.AddLoginAsync(user, new UserLoginInfo(userLogin.LoginProvider, userLogin.ProviderKey, userLogin.ProviderDisplayName)); if (result.Succeeded || (result.Errors != null && (result.Errors.Count() > 0 && result.Errors.First().Code.Equals("LoginAlreadyAssociated")))) { return new UserLoginResponseResult() { Code = 200, Data = userLogin } } ; if (!result.Succeeded) { return(new UserLoginResponseResult() { Code = (int)System.Net.HttpStatusCode.NotAcceptable, Message = result.Errors?.FirstOrDefault()?.Description }); } } } return(new UserLoginResponseResult() { Code = 400, Message = "Parameter is invalid." }); }
public async Task <ActionResponseResult> RemoveUserLogin([FromBody] ApplicationUserLogin userLogin) { if (userLogin != null) { return(await this._userManager.RemoveLoginAsync( new ApplicationUser() { Id = userLogin.UserId }, userLogin.LoginProvider, userLogin.ProviderKey) .ContinueWith((m) => { return new ActionResponseResult() { Code = 200 }; })); } return(new ActionResponseResult() { Code = 400, Message = "Parameter is invalid." }); }
private static UserLoginInfo FromApplicationUserLogin(ApplicationUserLogin login) { return(new UserLoginInfo(login.Provider, login.ProviderKey)); }
public async Task <ActionResult> SignInCallback(string returnUrl) { var authenticationManager = _authenticationManagerFactory(); var externalLoginInfo = await authenticationManager.GetExternalLoginInfoAsync(); if (externalLoginInfo == null) { return(RedirectToAction("Index", "Home")); } ApplicationUserExtended platformUser = null; //try yo take an user name from claims var userName = externalLoginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.Upn) ?? externalLoginInfo.DefaultUserName; if (string.IsNullOrWhiteSpace(userName)) { throw new InvalidOperationException("Received external login info does not have an UPN claim or DefaultUserName."); } var signInManager = _signInManagerFactory(); var externalLoginResult = await signInManager.ExternalSignInAsync(externalLoginInfo, false); if (externalLoginResult == SignInStatus.Failure) { //Need handle the two cases //first - when the VC platform user account already exists, it is just missing an external login info and //second - when user does not have an account, then create a new account for them platformUser = await _securityService.FindByNameAsync(userName, UserDetails.Full); var newExtenalLogin = new ApplicationUserLogin { LoginProvider = externalLoginInfo.Login.LoginProvider, ProviderKey = externalLoginInfo.Login.ProviderKey }; if (platformUser == null) { platformUser = new ApplicationUserExtended { UserName = userName, UserType = _authenticationOptions.AzureAdDefaultUserType, Logins = new ApplicationUserLogin[] { } }; } platformUser.Logins = platformUser.Logins.Concat(new[] { newExtenalLogin }).ToArray(); var result = await(platformUser.IsTransient() ? _securityService.CreateAsync(platformUser) : _securityService.UpdateAsync(platformUser)); if (!result.Succeeded) { var joinedErrors = string.Join(Environment.NewLine, result.Errors); throw new InvalidOperationException("Failed to save a VC platform account due the errors: " + joinedErrors); } //SignIn user in the system var aspNetUser = await signInManager.UserManager.FindByNameAsync(platformUser.UserName); await signInManager.SignInAsync(aspNetUser, isPersistent : true, rememberBrowser : true); } else if (externalLoginResult == SignInStatus.LockedOut || externalLoginResult == SignInStatus.RequiresVerification) { // TODO: handle user lock-out and two-factor authentication return(RedirectToAction("Index", "Home")); } if (platformUser == null) { platformUser = await _securityService.FindByNameAsync(userName, UserDetails.Full); } await _eventPublisher.Publish(new UserLoginEvent(platformUser)); return(Redirect(returnUrl)); }
public async Task <ClaimsIdentity> GetClaimsIdentity(LoginDto user, RequestMessageResponse errorResponse) { var result = await _signInManager.PasswordSignInAsync(user.Email, user.Password, false, true); if (result.Succeeded) { var appUser = _userManager.Users.SingleOrDefault(r => r.Email == user.Email); var roles = await _userManager.GetRolesAsync(appUser); IList <string> claims = new List <string>(); foreach (var roleName in roles) { if (_roleManager.SupportsRoleClaims) { var role = await _roleManager.FindByNameAsync(roleName); if (role != null) { var roleclaims = await _roleManager.GetClaimsAsync(role); foreach (var item in roleclaims) { if (!claims.Any(x => x == item.Value)) { claims.Add(item.Value); } } } } } // Save Login details #region Save Login Details HttpRequest request = _httpContextAccessor.HttpContext.Request; ConnectionInfo connection = _httpContextAccessor.HttpContext.Connection; string userAgent = "", remoteIpAddress = "", localIpAddress = "", languages = ""; if (request.Headers.ContainsKey(HeaderNames.UserAgent)) { userAgent = request.Headers[HeaderNames.UserAgent].ToString(); } if (request.Headers.ContainsKey(HeaderNames.AcceptLanguage)) { languages = request.Headers[HeaderNames.AcceptLanguage].ToString(); } remoteIpAddress = connection.RemoteIpAddress?.ToString(); localIpAddress = connection.LocalIpAddress?.ToString(); ApplicationUserLogin userLogin = new ApplicationUserLogin() { UserAgent = userAgent, AcceptLanguage = languages, RemoteIpAddress = remoteIpAddress, LocalIpAddress = localIpAddress, CreatedOnUtc = DateTime.UtcNow, User = appUser, }; await _userService.SaveUserLoginDetailsAsync(userLogin); #endregion return(await Task.FromResult <ClaimsIdentity>(GenerateClaimsIdentity(appUser.Email, appUser.Id, appUser.EmailConfirmed, roles, claims))); } else { // Check error message string errorMessage = ""; var appUser = _userManager.Users.SingleOrDefault(r => r.Email == user.Email); if (appUser == null) { errorMessage = "Invalid credentials"; } else { if (!await _userManager.IsEmailConfirmedAsync(appUser)) { errorMessage = "Email is not confirmed"; } else if (await _userManager.IsLockedOutAsync(appUser)) { errorMessage = "Account locked out till:" + appUser.LockoutEnd.Value.ToLocalTime(); } else if (!await _userManager.CheckPasswordAsync(appUser, user.Password)) { errorMessage = "Invalid credentials"; } } // Set error message errorResponse.Message = errorMessage; } return(await Task.FromResult <ClaimsIdentity>(null)); }
public async Task <ClaimsIdentity> GetClaimsIdentityForExternal(ApplicationUser appUser, RequestMessageResponse errorResponse) { // If email is not confirmed, CONFIRM IT if (!await _userManager.IsEmailConfirmedAsync(appUser)) { // Confirm email appUser.EmailConfirmed = true; await _userService.UpdateUser(appUser); } // Account lock out if (await _userManager.IsLockedOutAsync(appUser)) { // Set error message errorResponse.Message = "Account locked out till:" + appUser.LockoutEnd.Value.ToLocalTime(); return(await Task.FromResult <ClaimsIdentity>(null)); } // All good from here // Get roles var roles = await _userManager.GetRolesAsync(appUser); IList <string> claims = new List <string>(); foreach (var roleName in roles) { if (_roleManager.SupportsRoleClaims) { var role = await _roleManager.FindByNameAsync(roleName); if (role != null) { var roleclaims = await _roleManager.GetClaimsAsync(role); foreach (var item in roleclaims) { if (!claims.Any(x => x == item.Value)) { claims.Add(item.Value); } } } } } // Save Login details #region Save Login Details HttpRequest request = _httpContextAccessor.HttpContext.Request; ConnectionInfo connection = _httpContextAccessor.HttpContext.Connection; string userAgent = "", remoteIpAddress = "", localIpAddress = "", languages = ""; if (request.Headers.ContainsKey(HeaderNames.UserAgent)) { userAgent = request.Headers[HeaderNames.UserAgent].ToString(); } if (request.Headers.ContainsKey(HeaderNames.AcceptLanguage)) { languages = request.Headers[HeaderNames.AcceptLanguage].ToString(); } remoteIpAddress = connection.RemoteIpAddress?.ToString(); localIpAddress = connection.LocalIpAddress?.ToString(); ApplicationUserLogin userLogin = new ApplicationUserLogin() { UserAgent = userAgent, AcceptLanguage = languages, RemoteIpAddress = remoteIpAddress, LocalIpAddress = localIpAddress, CreatedOnUtc = DateTime.UtcNow, User = appUser }; await _userService.SaveUserLoginDetailsAsync(userLogin); #endregion return(await Task.FromResult <ClaimsIdentity>(GenerateClaimsIdentity(appUser.Email, appUser.Id, appUser.EmailConfirmed, roles, claims))); }
public ApplicationUser FindUserByLogin(ApplicationUserLogin userLogin) { return(FindUserInCache(c => c.FindUserByLogin(userLogin), () => FindUser(f => f._header._deleted == null && f.Logins.Any(l => l.ProviderKey == userLogin.ProviderKey)))); }
private static string GetUserLoginKey(ApplicationUserLogin userLogin) { return($"{userLogin.Provider},{userLogin.ProviderKey}"); }
/// <summary> /// Возвращает сведения о пользователе системы по его имени у внешнего провайдера. /// </summary> /// <param name="userLogin">Имя входа пользователя системы у внешнего провайдера.</param> /// <returns>Сведения о пользователе системы.</returns> public ApplicationUser FindUserByLogin(ApplicationUserLogin userLogin) { return(GetAdditionalUserCache(_usersByLogin, GetUserLoginKey(userLogin))); }
/// <summary> /// Register User Internal /// </summary> /// <param name="model"></param> /// <returns></returns> internal async Task <RegisterUserResult> RegisterInternal(RegisterGeneralModel model) { var userResult = new RegisterUserResult(); using (IUnitOfWork unitOfWork = UnitOfWork.Create()) { var checkUserEmail = unitOfWork.UserRepository.GetAll().FirstOrDefault(a => a.Email == model.Email || a.UserName == model.Email); if (checkUserEmail != null) { userResult.AddError(HttpStatusCode.BadRequest, 10, "This email is already taken ***"); return(userResult); } unitOfWork.BeginTransaction(); //Create user record var user = new ApplicationUser { Id = Guid.NewGuid().ToString(), FirstName = model.FirstName ?? string.Empty, LastName = model.LastName ?? string.Empty, UserName = model.Email, Email = model.Email, //AvatarFileId = model.AvatarFileId, HasTempPassword = true, CreatedById = DbConstants.AdminUserId, CreatedDate = DateTime.Now }; if (!string.IsNullOrEmpty(model.UserName)) { var names = model.UserName.Split(' '); user.FirstName = names[0]; user.LastName = names.Length > 1 ? names[1] : ""; } if (!string.IsNullOrEmpty(model.Password)) { user.PasswordHash = new PasswordHasher().HashPassword(model.Password); } user.AutopilotTrack = true; user.SecurityStamp = Guid.NewGuid().ToString(); #region Need To redo { ISchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = factory.GetScheduler(); JobDataMap dataMap = new JobDataMap(); dataMap["registermodel"] = model; dataMap["userId"] = user.Id; dataMap["OperationType"] = "Registration"; var job = JobBuilder.Create <UpdateContactJob>() .WithIdentity("UpdateContactJob").UsingJobData(dataMap) .Build(); var jobKey = new JobKey("UpdateContactJob"); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1") .StartAt(DateTime.Now) .ForJob(jobKey) .Build(); if (!scheduler.CheckExists(jobKey)) { scheduler.ScheduleJob(job, trigger); } scheduler.Start(); } #endregion unitOfWork.UserRepository.Insert(user); await unitOfWork.SaveAsync(); ApplicationUserRole userRole = new ApplicationUserRole(); userRole.RoleId = DataLayer.DbConstants.CustomerUserRole; userRole.UserId = user.Id; unitOfWork.UserRoleRepository.Insert(userRole); await unitOfWork.SaveAsync(); Address address = new Address(); address.CreatedById = user.Id; address.CreatedDate = DateTime.Now; unitOfWork.AddressRepository.Insert(address); await unitOfWork.SaveAsync(); CustomerDetails customer = new CustomerDetails(); customer.Id = Guid.NewGuid(); customer.CreatedById = user.Id; customer.CreatedDate = DateTime.Now; customer.UserId = user.Id; customer.ContactPhone = model.ContactPhone; customer.AddressId = address.Id; customer.ModifiedReason = "created"; unitOfWork.CustomerDetailsRepository.Insert(customer); await unitOfWork.SaveAsync(); if (!string.IsNullOrEmpty(model.Provider) && !string.IsNullOrEmpty(model.ExternalAccessToken)) { var loginInfo = await this.SignInManager.AuthenticationManager.GetExternalLoginInfoAsync(); ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(loginInfo.ExternalIdentity as ClaimsIdentity); ApplicationUserLogin userLogin = new ApplicationUserLogin(); userLogin.UserId = user.Id; userLogin.ProviderKey = loginInfo.Login.ProviderKey; userLogin.LoginProvider = loginInfo.Login.LoginProvider; unitOfWork.UserLoginRepository.Insert(userLogin); await unitOfWork.SaveAsync(); } unitOfWork.CommitTransaction(); if (model.Provider == null) { //Senf verification Email { string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = string.Format("{0}/#/confirm-email?userId={1}&code={2}", Url.Link("Default", new { controller = "account" }), user.Id, Uri.EscapeDataString(code)); await EmailNitificationHelper.Create().SendConfirmationEmail(user, UserManager, callbackUrl); } } userResult.UserId = user.Id; return(userResult); } }
public virtual async Task SaveUserLoginDetailsAsync(ApplicationUserLogin model) { await _context.AplicationUserLogins.AddAsync(model); await _context.SaveChangesAsync(); }