public Task AddLoginAsync(UserDto user, UserLoginInfo login) { if (user == null) { throw new ArgumentNullException("user"); } if (login == null) { throw new ArgumentNullException("login"); } User u = this.unitOfWork.GetRepository <User>().Get(us => us.UserId == user.Id).FirstOrDefault(); if (u == null) { throw new ArgumentException("IdentityUser does not correspond to a User entity.", "user"); } var l = new ExternalLogin { LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey, User = u }; u.Logins.Add(l); //unitOfWork.GetRepository<User>().Update(u); return(this.unitOfWork.SaveAsync()); }
public Task AddLoginAsync(IdentityUser user, UserLoginInfo login) { if (user == null) { throw new ArgumentNullException("user"); } if (login == null) { throw new ArgumentNullException("login"); } var usr = unitOfWork.UserRepository.GetSingle(u => u.UserId == user.Id, u => u.Logins); if (usr == null) { throw new ArgumentException("IdentityUser does not correspond to a User entity.", "user"); } var l = new ExternalLogin { LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey, User = usr }; usr.Logins.Add(l); unitOfWork.UserRepository.Update(usr); return(unitOfWork.CommitAsync()); }
public Task AddLoginAsync(ApplicationUser user, UserLoginInfo login) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (login == null) { throw new ArgumentNullException(nameof(login)); } var u = GetUserById(user.Id); if (u == null) { throw new ArgumentException("IdentityUser does not correspond to a User entity.", nameof(user)); } var l = new ExternalLogin { LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey, User = u }; u.Logins.Add(l); _userService.Save(u); return(Task.FromResult <object>(null)); }
public Task AddLoginAsync(IdentityUser user, UserLoginInfo login) { if (user == null) { throw new ArgumentNullException("user"); } if (login == null) { throw new ArgumentNullException("login"); } User user1 = this._userRepository.FindById(user.Id, false); if (user1 == null) { throw new ArgumentException("IdentityUser does not correspond to a User entity.", "user"); } ExternalLogin externalLogin = new ExternalLogin() { LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey, User = user1 }; user1.Logins.Add(externalLogin); this._userRepository.Update(user1); return(this._unitOfWork.CommitAsync()); }
public async Task AddLoginAsync(IdentityUser user, UserLoginInfo login) { if (user == null) { throw new ArgumentNullException("user"); } if (login == null) { throw new ArgumentNullException("login"); } var u = await _unitOfWork.UserRepository.FindById(user.Id); if (u == null) { throw new ArgumentException("IdentityUser does not correspond to a User entity.", "user"); } var l = new ExternalLogin { LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey, User = u }; u.Logins.Add(l); _unitOfWork.UserRepository.Update(u); await _unitOfWork.SaveChanges(); }
public Task AddLoginAsync(ApplicationUser user, UserLoginInfo login) { if (user == null) { throw new ArgumentNullException("user"); } if (login == null) { throw new ArgumentNullException("login"); } var myUser = _unitOfWork.UserRepository.FindById(user.Id); if (myUser == null) { throw new ArgumentException("ApplicationUser does not correspond to a User entity.", "user"); } var myLogin = new ExternalLogin { LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey, User = myUser }; myUser.Logins.Add(myLogin); _unitOfWork.UserRepository.Update(myUser); return(_unitOfWork.CommitAsync()); }
public Task AddLoginAsync(IdentityUser user, UserLoginInfo login) { if (user == null) { throw new ArgumentNullException("user"); } if (login == null) { throw new ArgumentNullException("login"); } var u = _securityDbService.UserRepository.GetById(user.Id); if (u == null) { throw new ArgumentException("IdentityUser does not correspond to a User entity.", "user"); } var l = new ExternalLogin { LoginProvider = login.LoginProvider, ProviderKey = login.ProviderKey, User = u }; u.Logins.Add(l); _securityDbService.UserRepository.Update(u); return(_securityDbService.SaveChangesAsync()); }
public IHttpActionResult DeleteExternalLogin(int id) { // Allow only for authorized user var userToCheck = _userRepository.FirstOrDefault(u => u.UserName == User.Identity.Name); if (!userToCheck.Authorized) { return(Unauthorized()); } // Get the DB externalLogin corresponding to the externalLogin ID ExternalLogin dbExternalLogin = _externalLoginRepository.GetByID(id); if (dbExternalLogin == null) { return(NotFound()); } // Remove the externalLogin _externalLoginRepository.Delete(dbExternalLogin); try { _unitOfWork.Commit(); } catch (Exception e) { throw new Exception("Unable to delete the externalLogin from the database", e); } return(Ok(Mapper.Map <ExternalLoginModel>(dbExternalLogin))); }
private void HandleEvent(UserLoginAdded <TKey> evt) { var(normalizedEmail, normalizedUser, logins, claims) = reverseLookup[evt.UserId]; var login = new ExternalLogin(evt.UserLoginInfo.LoginProvider, evt.UserLoginInfo.ProviderKey); logins.Add(login); existingLogins[login] = evt.UserId; }
public virtual void AddOrUpdateExternalLogin(UserAccount account, string provider, string id, IEnumerable <Claim> claims = null) { if (account == null) { throw new ArgumentNullException(nameof(account)); } _logger.LogInformation(GetLogMessage($"called for accountId: {account.UserId}")); if (string.IsNullOrWhiteSpace(provider)) { _logger.LogError(GetLogMessage("failed -- null provider")); throw new ArgumentNullException(nameof(provider)); } if (string.IsNullOrWhiteSpace(id)) { _logger.LogError(GetLogMessage("failed -- null id")); throw new ArgumentNullException(nameof(id)); } var otherAcct = GetByExternalLogin(provider, id); if (otherAcct != null && otherAcct.UserId != account.UserId) { _logger.LogError(GetLogMessage("failed -- adding linked account that is already associated with another account")); throw new ValidationException(GetValidationMessage("ExternalLoginAlreadyInUse")); } //RemoveExternalLoginClaims(account, provider, id); var linked = GetExternalLogin(account, provider, id); if (linked == null) { linked = new ExternalLogin { LoginProvider = provider, ProviderKey = id, LastLogin = UtcNow }; account.AddExternalLogin(linked); AddEvent(new ExternalLoginAddedEvent { Account = account, ExternalLogin = linked }); _logger.LogTrace(GetLogMessage("linked account added")); } else { linked.LastLogin = UtcNow; } account.LastLogin = UtcNow; Update(account); }
public async Task <IActionResult> ExternalLoginConfirmation(ExternalLogin model, string returnUrl = null) { if (!ModelState.IsValid) { return(View(model)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(View(nameof(Error))); } var user = await _userManager.FindByEmailAsync(model.Email); IdentityResult result; if (user != null) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); return(RedirectToLocal(returnUrl)); } } else { model.Principal = info.Principal; user = _mapper.Map <User>(model); result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { //TODO: Send an emal for the email confirmation and add a default role as in the Register action await _signInManager.SignInAsync(user, isPersistent : false); return(RedirectToLocal(returnUrl)); } } } foreach (var error in result.Errors) { ModelState.TryAddModelError(error.Code, error.Description); } return(View(nameof(ExternalLogin), model)); }
public IHttpActionResult GetExternalLogin(int id) { ExternalLogin dbExternalLogin = _externalLoginRepository.GetByID(id); if (dbExternalLogin == null) { return(NotFound()); } return(Ok(Mapper.Map <ExternalLoginModel>(dbExternalLogin))); }
private void LoginActivity_Click(object sender, EventArgs e) { View dialogLayout = LayoutInflater.Inflate(Resource.Layout.DialogButtonsX2, null); var termsButton = dialogLayout.FindViewById <Button>(Resource.Id.dialogBtn1); termsButton.Text = Resources.GetString(Resource.String.LoginOpenTerms); termsButton.Click += (args, o) => { Intent browserIntent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse( ConfidentialData.api + "terms")); StartActivity(browserIntent); }; var privacyButton = dialogLayout.FindViewById <Button>(Resource.Id.dialogBtn2); privacyButton.Text = Resources.GetString(Resource.String.LoginOpenPrivacy); privacyButton.Click += (args, o) => { Intent browserIntent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse( ConfidentialData.api + "privacypolicy")); StartActivity(browserIntent); }; new global::Android.Support.V7.App.AlertDialog.Builder(this) .SetTitle(Resource.String.LoginTermsTitle) .SetMessage(Resource.String.LoginTerms) .SetView(dialogLayout) .SetNegativeButton(Resource.String.dialog_cancel, (a, args) => { }) .SetPositiveButton(Resource.String.LoginAgreeTerms, (a, args) => { string buttonText = ((Button)sender).Text; ExternalLogin chosen = providers.FirstOrDefault(prov => prov.Name == buttonText); if (chosen == null) { return; } chromeManager = new CustomTabsActivityManager(this); // build custom tab var builder = new CustomTabsIntent.Builder(chromeManager.Session) .SetShowTitle(true) .EnableUrlBarHiding(); var customTabsIntent = builder.Build(); customTabsIntent.Intent.AddFlags(ActivityFlags.NoHistory); chromeManager.Warmup(0L); customTabsIntent.LaunchUrl(this, global::Android.Net.Uri.Parse(ConfidentialData.api + chosen.Url)); }) .Show(); }
public Task AddLoginAsync(User user, UserLoginInfo login) { return(Task.Run(() => { var externalLogin = new ExternalLogin(); externalLogin.ProviderKey = login.ProviderKey; externalLogin.ProviderName = login.LoginProvider; externalLogin.User = user; externalLogin.Save(); })); }
public Task RemoveLoginAsync(User user, UserLoginInfo login) { return(Task.Run(() => { var externalLogin = ExternalLogin.LoadByProviderKey(login.ProviderKey); if (externalLogin != null) { externalLogin.Delete(); } })); }
private async Task GetExternalLoginProviders() { var bounds = UIScreen.MainScreen.Bounds; // show the loading overlay on the UI thread using the correct orientation sizing loadPop = new LoadingOverlay(bounds); View.Add(loadPop); string fullUrl = "/api/Account/ExternalLogins?returnUrl=/callback&generateState=true"; ServerResponse <ExternalLogin[]> res = await ServerUtils.Get <ExternalLogin[]>(fullUrl, false); loadPop.Hide(); if (res.Success) { providers = res.Data; for (int i = 0; i < providers.Length; i++) { UIButton button = new UIButton(); nfloat buttonWidth = PromptLabel.Frame.Width; nfloat buttonYPos = PromptLabel.Frame.GetMaxY() + 20f + (60 * i); button.Frame = new CGRect(0f, buttonYPos, buttonWidth, 60f); button.SetTitle(providers[i].Name, UIControlState.Normal); button.TitleLabel.Font = UIFont.SystemFontOfSize(19); button.TouchUpInside += (sender, e) => { notificationToken = NSNotificationCenter.DefaultCenter.AddObserver(new NSString("ParkLearnLoginCallback"), OnLoginResult); // Use the button's title to find the appropriate provider ExternalLogin thisLogin = providers.FirstOrDefault(p => p.Name == ((UIButton)sender).Title(UIControlState.Normal)); if (thisLogin == null) { Console.WriteLine("Provider button is null"); return; } LoginAfterTerms(thisLogin.Url); }; PromptLabel.Superview.AddSubview(button); } } else { // Show error and retry button var errorAlert = UIAlertController.Create("Connection Error", "Couldn't load login info from the server. Please try again.", UIAlertControllerStyle.Alert); errorAlert.AddAction(UIAlertAction.Create("Retry", UIAlertActionStyle.Default, (a) => { var suppressAsync = GetExternalLoginProviders(); })); PresentViewController(errorAlert, true, null); } }
public static AuthenticationBuilder AddFacebookIf( this AuthenticationBuilder builder, bool condition, ExternalLogin config, string accessDeniedPath) { return(condition ? builder.AddFacebook(options => { options.AppId = config.AppId; options.AppSecret = config.AppSecret; options.AccessDeniedPath = accessDeniedPath; }) : builder); }
public static AuthenticationBuilder AddTwitterIf( this AuthenticationBuilder builder, bool condition, ExternalLogin config, string accessDeniedPath) { return(condition ? builder.AddTwitter(options => { options.ConsumerKey = config.AppId; options.ConsumerSecret = config.AppSecret; options.RetrieveUserDetails = true; options.AccessDeniedPath = accessDeniedPath; }) : builder); }
public Task <IdentityUser> FindAsync(UserLoginInfo login) { if (login == null) { throw new ArgumentNullException("login"); } IdentityUser identityUser = null; ExternalLogin byProviderAndKey = this._externalLoginRepository.GetByProviderAndKey(login.LoginProvider, login.ProviderKey); if (byProviderAndKey != null) { identityUser = this.GetIdentityUser(byProviderAndKey.User); } return(Task.FromResult <IdentityUser>(identityUser)); }
private void FindByLogin(ExternalLogin external, IActorRef sender) { if (existingLogins.TryGetValue(external, out TKey key)) { if (!userActors.TryGetValue(key, out IActorRef actor)) { userActors[key] = actor = createUserActor(key); } actor.Tell(ReturnDetails.Instance, sender); } else { sender.Tell(NilMessage.Instance); } }
public async Task AddLoginAsync(User user, UserLoginInfo login) { using (var stream = OpenUserDatabase()) { var db = ReadUserDatabase(stream); var persistenceUser = db.FindUser(user.Id); if (persistenceUser == null) { return; } var logins = new List <ExternalLogin>(persistenceUser.ExternalLogins ?? Enumerable.Empty <ExternalLogin>()); logins.Add(ExternalLogin.FromUserLoginInfo(login)); persistenceUser.ExternalLogins = logins.ToArray(); UpdateUserDatabase(stream, db); } }
public async Task <IActionResult> AddStockConection(AddStockConnectionViewModel model, int id) { var user = await userManager.FindByNameAsync(User.Identity.Name); ExternalLogin externalLogin = new ExternalLogin { Login = model.Login, Password = model.Password, StockId = id, // ApplicationUserId = user.Id }; user.AvaliableStocks.Add(externalLogin); IdentityResult result = await userManager.UpdateAsync(user); // externalLoginRepostory.Add(externalLogin); return(RedirectToAction("index")); }
/// <summary> /// Externals the login. /// </summary> /// <param name="request">The request.</param> /// <param name="ipAddress">The ip address.</param> /// <returns></returns> public async Task <object> ExternalLogin(GoogleAuthenticationRequest request, string ipAddress) { var internalUserFilter = Builders <User> .Filter.Eq("email", request.User.Email); var existInternalUser = await userRepository.FindAsync(internalUserFilter); if (existInternalUser != null) { var finder = Builders <ExternalLogin> .Filter.Eq("email", request.User.Email); var existExternalLogin = await externalLoginRepository.FindAsync(finder); if (existExternalLogin == null) { var externalLogin = new ExternalLogin() { Email = request.User.Email, LoginProvider = Constants.ExternalLoginConstants.GOOGLE_EXTERNAL_PROVIDER }; await externalLoginRepository.AddAsync(externalLogin); } Account account = accountRepository.GetAll().FirstOrDefault(x => x.Email == existExternalLogin.Email); string jwtToken = accountService.generateJwtToken(account); RefreshToken refreshToken = accountService.generateRefreshToken(ipAddress); account.RefreshTokens.Add(refreshToken); accountService.removeOldRefreshTokens(account); accountRepository.Update(account, account.Id); AuthenticateResponse response = mapper.Map <AuthenticateResponse>(account); response.JwtToken = jwtToken; response.RefreshToken = refreshToken.Token; return(response); } else { return(request); } }
public Task <UserDto> FindAsync(UserLoginInfo login) { if (login == null) { throw new ArgumentNullException("login"); } UserDto userDto = default(UserDto); ExternalLogin l = this.unitOfWork.GetRepository <ExternalLogin>() .Get(log => (log.ProviderKey == login.ProviderKey) && (log.LoginProvider == login.LoginProvider)) .FirstOrDefault(); if (l != null) { userDto = Mapper.Map <User, UserDto>(l.User); } return(Task.FromResult <UserDto>(userDto)); }
public Task RemoveLoginAsync(IdentityUser user, UserLoginInfo login) { if (user == null) { throw new ArgumentNullException("user"); } if (login == null) { throw new ArgumentNullException("login"); } User user1 = this._userRepository.FindById(user.Id, false); if (user1 == null) { throw new ArgumentException("IdentityUser does not correspond to a User entity.", "user"); } ExternalLogin externalLogin = user1.Logins.FirstOrDefault <ExternalLogin>((ExternalLogin x) => (x.LoginProvider != login.LoginProvider ? false : x.ProviderKey == login.ProviderKey)); user1.Logins.Remove(externalLogin); this._userRepository.Update(user1); return(this._unitOfWork.CommitAsync()); }
public async Task <ActionResult> RemoveLogin(string userName, ExternalLogin model) { var user = await this.userManager.FindByNameAsync(userName); if (user == null) { return(this.NotFound()); } var userId = await this.userManager.GetUserIdAsync(user); if (string.IsNullOrEmpty(userId)) { return(this.NotFound()); } var currentUserId = this.userManager.GetUserId(this.User); if (!userId.Equals(currentUserId, StringComparison.OrdinalIgnoreCase) && !this.User.IsInRole("Admin")) { return(this.Forbid()); } var result = await this.userManager.RemoveLoginAsync(user, model.ProviderName, model.ExternalUserId); if (!result.Succeeded) { foreach (var error in result.Errors) { this.ModelState.AddModelError(string.Empty, error.Description); } return(this.BadRequest(this.ModelState)); } return(this.Ok()); }
public async Task <object> RedeemToken([FromBody] ExternalLogin options) { // check for server-generated nonce, and make sure it was issued recently if (!IssuedNonces.Any(o => o.Hash == options.Nonce)) { this.ThrowLocalizedServiceException(Constants.InvalidNonce); } Nonce nonce = IssuedNonces.FirstOrDefault(o => o.Hash == options.Nonce); if (nonce.Processing) { this.ThrowLocalizedServiceException(Constants.InProgressNonce); } if (nonce.Created.AddMinutes(30) < DateTime.UtcNow) { IssuedNonces.Remove(nonce); this.ThrowLocalizedServiceException(Constants.ExpiredNonce); } nonce.Update(true); // swap the external access token for a local application token var identity = await this.externalAuthService.RedeemToken(options); if (identity == null) { this.ThrowLocalizedServiceException(Constants.UnknownUser); } // remove the original nonce, and revoke the external access token, as they are longer required IssuedNonces.Remove(nonce); this.externalAuthService.RevokeToken(options.ProviderId, options.AccessToken); return(await this.tokenService.IssueToken(identity, identity.Name)); }
public IEnumerable <ExternalLogin> GetExternalLogins(string returnUrl, bool generateState = false) { IEnumerable <AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes(); List <ExternalLogin> logins = new List <ExternalLogin>(); string state; if (generateState) { const int strengthInBits = 256; state = RandomOAuthStateGenerator.Generate(strengthInBits); } else { state = null; } foreach (AuthenticationDescription description in descriptions) { ExternalLogin login = new ExternalLogin { Name = description.Caption, Url = Url.Route("ExternalLogin", new { provider = description.AuthenticationType, response_type = "token", client_id = Startup.PublicClientId, redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, state = state }), State = state }; logins.Add(login); } return(logins); }
public IHttpActionResult PostExternalLogin(ExternalLoginModel externalLogin) { // Validate request if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Check that the corresponding user exists if (!_userRepository.Any(u => u.Id == externalLogin.UserID)) { throw new Exception("Unable to add the external login to the database, as it does not correspond to a user"); } //Set up new ExternalLogin object, populated from input externalLogin ExternalLogin dbExternalLogin = new ExternalLogin(); dbExternalLogin.Update(externalLogin); // Add the new ExternalLogin object to the DB _externalLoginRepository.Add(dbExternalLogin); // Save the changes in the database try { _unitOfWork.Commit(); } catch (Exception e) { throw new Exception("Unable to add the externalLogin to the database", e); } // Set externalLogin ID in ExternalLoginModel object with the ID // that was set in the DB externalLogin after db.SaveChanges externalLogin.ExternalLoginID = dbExternalLogin.ExternalLoginID; return(CreatedAtRoute("DefaultApi", new { id = externalLogin.ExternalLoginID }, externalLogin)); }
public void Init() { instance = new ExternalLogin(); }