/// <summary> /// Register user /// </summary> /// <param name="data">Login data</param> /// <param name="hasManager">Has user manager</param> /// <returns> /// <see cref="IdentityResult"/>s object containing the result of registration. /// </returns> private IdentityResult RegisterUser(RegisterViewModel data, bool hasManager) { IdentityResult result = IdentityResult .Failed(); var userDto = data .ToDto(); userDto.UserRole = hasManager ? "Manager" : "Employee"; var findUserTask = ServiceUserManager .FindByNameAsync(userDto.Login); findUserTask .Wait(); var alreadyRegistered = (findUserTask.Result != null); if (alreadyRegistered) { throw new Exception(String.Format( "User {0} already exists!", userDto.Login)); } var user = new ServiceUser(userDto); var createUserTask = ServiceUserManager .CreateAsync(user); createUserTask .Wait(); result = createUserTask .Result; if (result == IdentityResult.Success) { findUserTask = ServiceUserManager .FindByNameAsync(userDto.Login); findUserTask .Wait(); user = findUserTask .Result; LoginUser(user); } return(result); }
public async Task <IHttpActionResult> RegisterUsingExternalProvider(ProviderAndAccessToken model) { ExternalProvider externalProvider; if (!Enum.TryParse <ExternalProvider>(model.Provider, out externalProvider)) { return(BadRequest($"Invalid provider : {model.Provider}")); } dynamic userData = AuthorizeByExternalProvider(model, externalProvider); ServiceUser user = await UserManager.FindAsync(new UserLoginInfo(model.Provider, userData.id)); if (user != null || (await UserManager.FindByEmailAsync(userData.userName) != null || await UserManager.FindByNameAsync(userData.userName) != null)) { return(BadRequest($"{userData.userName} is already registered")); } user = new ServiceUser() { UserName = userData.userName, Email = userData.userName }; IdentityResult result = await UserManager.CreateAsync(user); if (!result.Succeeded) { return(GetErrorResult(result)); } result = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(model.Provider, userData.id)); if (!result.Succeeded) { return(GetErrorResult(result)); } user = await UserManager.FindAsync(new UserLoginInfo(model.Provider, userData.id)); return(Ok(new { access_token = getServiceAccessToken(user) })); }