public async Task <IActionResult> ChangePasswordRequestedAsync([FromQuery] string username, [FromQuery] string token) { if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(token)) { return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message])); } var result = new ChangeForgotenPasswordViewModel { Username = Encoding.UTF8.GetString(Convert.FromBase64String(username)), Token = token }; await Task.CompletedTask.ConfigureAwait(true); return(Ok(result)); }
public async Task <IActionResult> Signin([FromQuery] string provider = "Google") { var deviceHeader = GetDeviceInfosFromHeader(); if (deviceHeader == null) { return(BadRequest(DataTransferer.DefectiveEntry().Message)); } var userdata = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(deviceHeader))); var redirecturl = $"/api/externalauthentication/signincallback?userdata={userdata}"; var authprops = new AuthenticationProperties { AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddDays(7), IsPersistent = true, RedirectUri = redirecturl }; Response.Redirect(redirecturl); await Response.CompleteAsync().ConfigureAwait(true); return(Challenge(authprops, provider)); }
public async Task <IActionResult> SigninCallbackAsync(string userData = null, string remoteError = null) { try { if (string.IsNullOrWhiteSpace(userData)) { Log.Error("userData is not defined"); return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message])); } var headerbindingmodel = JsonConvert.DeserializeObject <Device>(Encoding.UTF8.GetString(Convert.FromBase64String(userData))); if (headerbindingmodel == null || string.IsNullOrWhiteSpace(headerbindingmodel.DeviceId) || string.IsNullOrWhiteSpace(headerbindingmodel.DeviceName) || string.IsNullOrWhiteSpace(headerbindingmodel.DeviceType)) { Log.Error("userData is not valid"); return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message])); } // read external identity from the temporary cookie var authenticationResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(true); if (!authenticationResult.Succeeded) { Log.Error("External authentication failed"); return(Problem(_localizer[DataTransferer.ExternalAuthenticationFailed().Message])); } // retrieve claims of the external user var claimPrincipal = authenticationResult.Principal; if (claimPrincipal == null) { Log.Error("External authentication user principal error"); return(Problem(_localizer[DataTransferer.ExternalAuthenticationUserError().Message])); } // transform claims list to model var externalUser = GetExternalUser(claimPrincipal.Claims); if (string.IsNullOrWhiteSpace(externalUser.Email)) { Log.Error("External authentication user email not found"); return(Problem(_localizer[DataTransferer.ExternalAuthenticationEmailError().Message])); } if (externalUser.ProviderId == AccountProvider.Clipboardy) { Log.Error("External signup with unknown ProviderId"); return(Problem(_localizer[DataTransferer.ExternalAuthenticationWithUnknownProvider().Message])); } externalUser.DeviceId = headerbindingmodel.DeviceId; externalUser.DeviceName = headerbindingmodel.DeviceName; externalUser.DeviceType = headerbindingmodel.DeviceType; var accountprofile = await _accountProfileService.FirstAsync(new AccountProfileGetFirstSchema { TypeId = AccountProfileType.Email.ToInt(), LinkedId = externalUser.Email }).ConfigureAwait(true); if (accountprofile == null) { Log.Debug($"User {User.Identity.Name} try to sign in for first time at {DateTime.UtcNow}"); return(Ok(_accountService.ExternalSignupAsync(externalUser))); } else { Log.Debug($"Account with Id={accountprofile.AccountId} try to sign in at {DateTime.UtcNow}"); var result = await _accountService.ExternalSigninAsync(externalUser, accountprofile).ConfigureAwait(false); switch (result.Code) { case 200: return(Ok(result.Data)); case 500: return(Problem(_localizer[result.Message])); default: return(BadRequest(_localizer[result.Message])); } } } catch (Exception ex) { Log.Error(ex, ex.Source); return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message])); } }
public async Task <IServiceResult> ExternalSigninAsync(ExternalUserBindingModel externalUser, AccountProfileResult accountProfile) { if (accountProfile == null && accountProfile.AccountId.HasValue) { return(DataTransferer.DefectiveEntry()); } if (accountProfile.StatusId != Status.Active) { return(DataTransferer.UserIsNotActive()); } var now = DateTime.UtcNow; var accountQuery = new AccountGetFirstSchema { Id = accountProfile.AccountId, StatusId = Status.Active.ToInt() }; var account = await FirstAsync(accountQuery); if (account == null) { return(DataTransferer.UserNotFound()); } // todo: check the account using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { try { var accountDeviceQuery = new AccountDeviceGetFirstSchema { AccountId = account.Id, DeviceId = externalUser.DeviceId }; var accountDevice = await _accountDeviceService.FirstAsync(accountDeviceQuery); if (accountDevice == null) { return(DataTransferer.DeviceIdNotFound()); } int deviceId; if (accountDevice != null) { deviceId = accountDevice.Id.Value; // set a new token await _accountDeviceService.UpdateAsync(new AccountDeviceUpdateSchema { Id = accountDevice.Id.Value }); } else { // create new device for account deviceId = await _accountDeviceService.AddAsync(new AccountDeviceAddSchema { AccountId = account.Id, DeviceId = externalUser.DeviceId, DeviceName = externalUser.DeviceName, DeviceType = externalUser.DeviceType, CreatedAt = now, StatusId = Status.Active.ToInt() }); } // clean forgot password tokens //account.Id.Value, transaction await _accountProfileService.CleanForgotPasswordTokensAsync(account.Id.Value); //if(accountProfileCleanTokens.StatusCode != 200) { // Log.Error($"Can't update 'ForgotPasswordTokens' to NULL for AccountId={account.Id}"); // return DataTransferer.SomethingWentWrong(); //} // set last signed in at var accountUpdate = new AccountUpdateSchema { Id = account.Id.Value, LastSignedinAt = now }; await UpdateAsync(accountUpdate); if (accountUpdate.StatusCode != 200) { Log.Error($"Can't update 'LastSignedinAt' after a successfully signing in for AccountId={account.Id}"); } transaction.Complete(); var token = _jwtHandler.Bearer(new Account(account.Id.Value, deviceId, account.Username, now).ToClaimsIdentity()); return(DataTransferer.Ok(token)); } catch (Exception ex) { Log.Error(ex, ex.Source); return(DataTransferer.InternalServerError(ex)); } } }
public async Task <IActionResult> SignupAsync([FromBody] SignupBindingModel collection) { // todo: Captcha if (collection == null) { return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message])); } if (string.IsNullOrEmpty(collection?.Username)) { return(BadRequest(_localizer[DataTransferer.DefectiveEmailOrCellPhone().Message])); } Log.Debug($"A User is trying to register with this data: {JsonConvert.SerializeObject(collection)}"); collection.Username = collection.Username.Trim(); try { if (collection.Username.IsPhoneNumber()) { collection.Phone = collection.Username; if (await _accountProfileService.FirstAsync(new AccountProfileGetFirstSchema { LinkedId = collection.Phone }).ConfigureAwait(true) != null) { return(BadRequest(_localizer[DataTransferer.CellPhoneAlreadyExists().Message])); } } else if (new EmailAddressAttribute().IsValid(collection.Username)) { collection.Email = collection.Username; if (await _accountProfileService.FirstAsync(new AccountProfileGetFirstSchema { LinkedId = collection.Email }).ConfigureAwait(true) != null) { return(BadRequest(_localizer[DataTransferer.EmailAlreadyExists().Message])); } } else { return(BadRequest(_localizer[DataTransferer.InvalidEmailOrCellPhone().Message])); } if (string.IsNullOrEmpty(collection.Password) && string.IsNullOrEmpty(collection.ConfirmPassword)) { return(BadRequest(_localizer[DataTransferer.DefectivePassword().Message])); } if (collection.Password != collection.ConfirmPassword) { return(BadRequest(_localizer[DataTransferer.PasswordsMissmatch().Message])); } if (string.IsNullOrEmpty(collection.DeviceId) || string.IsNullOrEmpty(collection.DeviceName)) { return(BadRequest(_localizer[DataTransferer.UnofficialRequest().Message])); } var result = await _accountService.SignupAsync(collection).ConfigureAwait(true); switch (result.Code) { case 200: return(Ok(result.Data)); case 400: return(BadRequest(result.Message)); case 500: default: return(Problem(result.Message)); } } catch (Exception ex) { Log.Error(ex, ex.Source); return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message])); } }
public async Task <ActionResult> ActivateAccountAsync([FromBody] ActivateAccountBindingModel collection) { if (collection == null || string.IsNullOrWhiteSpace(collection.Username) || string.IsNullOrWhiteSpace(collection.Code)) { return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message])); } var query = new AccountProfileGetFirstSchema { LinkedId = collection.Username }; if (collection.Username.IsPhoneNumber()) { query.TypeId = AccountProfileType.Phone.ToInt(); } else if (new EmailAddressAttribute().IsValid(collection.Username)) { query.TypeId = AccountProfileType.Email.ToInt(); } else { return(BadRequest(_localizer[DataTransferer.InvalidEmailOrCellPhone().Message])); } try { var accountProfile = await _accountProfileService.FirstAsync(query).ConfigureAwait(true); if (accountProfile == null) { if (query.TypeId == AccountProfileType.Phone.ToInt()) { return(BadRequest(_localizer[DataTransferer.PhoneNotFound().Message])); } if (query.TypeId == AccountProfileType.Email.ToInt()) { return(BadRequest(_localizer[DataTransferer.EmailNotFound().Message])); } } var activationCode = _memoryCache.Get(collection.Username); if (activationCode == null) { return(BadRequest(_localizer[DataTransferer.ActivationCodeRequestedNotFound().Message])); } if (collection.Code != activationCode.ToString()) { return(BadRequest(_localizer[DataTransferer.ActivationCodeRequestedNotFound().Message])); } _memoryCache.Remove(collection.Username); var accountProfileQuery = new AccountProfileUpdateSchema { Id = accountProfile.Id.Value, StatusId = Status.Active.ToInt() }; await _accountProfileService.UpdateAsync(accountProfileQuery).ConfigureAwait(true); return(Ok(_localizer[DataTransferer.AccountActivated().Message])); } catch (Exception ex) { Log.Error(ex, ex.Source); return(Problem()); } }