private HttpResponseMessage ProcessClientCredentialsRequest(ValidatedRequest validatedRequest) { Tracing.Information("Processing refresh token request"); var sts = new TokenService(_config.GlobalConfiguration); var response = sts.CreateTokenResponse(validatedRequest); return Request.CreateTokenResponse(response); }
public TokenController( IResourceOwnerCredentialValidation rocv, IAuthorizationServerConfiguration config, IStoredGrantManager handleManager, IAssertionGrantValidation assertionGrantValidator, TokenService tokenService) { _rocv = rocv; _config = config; _handleManager = handleManager; _assertionGrantValidator = assertionGrantValidator; _tokenService = tokenService; }
public IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, TokenService.RequestDetails requestDetails) { var username = principal.Identity.Name; var claims = new List<Claim>(from c in principal.Claims select c); if (!String.IsNullOrEmpty(username)) { using (var context = new PortalEntities()) { var user = context.User.FirstOrDefault(p => p.Mail == username); if (user != null) { claims.Add(new Claim("IsAdmin", user.IsAdmin.ToString())); } } claims.Add(new Claim(ClaimTypes.Email, username)); } return claims; }
public async Task <ActionResult> MakePayment(decimal cost, decimal taxCharge, decimal penalty) { try { long communityAct = Convert.ToInt64(Session["CURRENT_COMU"]); string paymentType = "CC"; // CreditCard bool makePayment = false; long userId = (long)Session["USER_ID"]; user curUser = entities.users.Find(userId); long adminId = (long)curUser.create_userid; fee feeItem = entities.fees.Where(m => m.user_id == adminId && m.community_id == communityAct).FirstOrDefault(); bank adminBankItem = entities.banks.Find(feeItem.bank_id); string bank_account = adminBankItem.account_number; string routing_number = adminBankItem.route_number; string account_name = adminBankItem.account_name; user adminUser = entities.users.Find(adminId); decimal totalAmount = cost + taxCharge + penalty; creditcard creditcardItem = entities.creditcards.Where(m => m.user_id == userId).FirstOrDefault(); StripeConfiguration.SetApiKey(ep.GetStripeSecretKey()); if (creditcardItem != null) { DateTime expire_date = (DateTime)creditcardItem.expiration_date; var options = new TokenCreateOptions { Card = new CreditCardOptions { Number = creditcardItem.card_number, //"4000 0000 0000 0077", //creditcardItem.card_number,//"4242424242424242" ExpYear = expire_date.Year, //2020 ExpMonth = expire_date.Month, Cvc = creditcardItem.ccv } }; var service = new TokenService(); Token stripeToken = service.Create(options); int pc = await PaymentCredit(stripeToken.Id, Convert.ToInt32(cost * 100), bank_account, routing_number, account_name); if (pc == 1) { paymentType = "CC"; makePayment = true; } } else { bank userBank = entities.banks.Where(m => m.user_id == userId).FirstOrDefault(); if (userBank != null) { var options = new TokenCreateOptions { BankAccount = new BankAccountOptions { Country = "US", Currency = "usd", AccountHolderName = userBank.account_name, //"Jenny Rosen" AccountHolderType = "individual", RoutingNumber = userBank.route_number, //"110000000" AccountNumber = userBank.account_number //"000123456789" } }; var service = new TokenService(); Token stripeToken = service.Create(options); int ach = await PaymentAch(stripeToken.Id, Convert.ToInt32(totalAmount * 100), bank_account, routing_number); if (ach == 1) { paymentType = "ACH"; makePayment = true; } } } if (makePayment == true) { transaction transItem = new transaction(); if (transItem.balance != null) { decimal originBalance = (decimal)transItem.balance; transItem.balance = originBalance + totalAmount; } else { transItem.balance = totalAmount; } transItem.credit = 0; transItem.debit = totalAmount; transItem.date_info = DateTime.Now; transItem.kind = "Factura"; transItem.state = "Factura"; transItem.trans_id = ""; entities.transactions.Add(transItem); payment paymentItem = new payment(); paymentItem.method = paymentType; paymentItem.date_issue = DateTime.Now; paymentItem.date_payment = null; paymentItem.email = adminUser.email; paymentItem.first_name = adminUser.first_name1; paymentItem.surname = adminUser.last_name1; paymentItem.to_user_id = adminId; paymentItem.quantity = totalAmount; paymentItem.user_id = userId; paymentItem.state = true; entities.payments.Add(paymentItem); entities.SaveChanges(); } return(Redirect(Url.Action("estado", "cuotas"))); } catch (Exception ex) { return(Redirect(Url.Action("balance", "cuotas"))); } }
public Task <bool> GetCodeAsync(string phone) { return(TokenService.GetCode(phone)); }
public async void RegisterUser(Object sender, EventArgs e) { try { string firstNameVar = firstName.Text; string lastNameVar = lastName.Text; int dobDayVar = Convert.ToInt32(dobDay.Text); int dobMonthVar = Convert.ToInt32(dobMonth.Text); int dobYearVar = Convert.ToInt32(dobYear.Text); string addressLine1Var = addressLine1.Text; string addressLine2Var = addressLine2.Text; string postalCodeVar = postalCode.Text; var statesPickerVar = statesPicker.Items[statesPicker.SelectedIndex]; string routingNumberVar = routingNumber.Text; string accountNumberVar = accountNumber.Text; string cityVar = city.Text; StripeConfiguration.SetApiKey("sk_test_Q5wSnyXL03yN0KpPaAMYttOb"); //-------Get IP Address---------// var MyIp = ""; string uploadId = ""; foreach (IPAddress adress in Dns.GetHostAddresses(Dns.GetHostName())) { MyIp = adress.ToString(); break; } //------Camera will Open User take the Picture Of Idenity Card-----------// /* var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions * { * Directory = "Sample", * Name = "test.jpg", * PhotoSize = Plugin.Media.Abstractions.PhotoSize.Small * * }); * * //-------Upload File in stripe and return the file Id -------------// * using (FileStream stream = System.IO.File.Open(file.Path, FileMode.Open)) * { * var fileService = new FileService(); * var fileCreateOptions = new FileCreateOptions * { * File = stream, * Purpose = "identity_document", * }; * Stripe.File upload = fileService.Create(fileCreateOptions); * uploadId = upload.Id; * } */ //------Set File.id-----/// AccountVerificationOptions verifiy = new AccountVerificationOptions { DocumentId = uploadId, }; //--------Create User Account Legal Entity-----------// AccountLegalEntityOptions legalEntity = new AccountLegalEntityOptions { FirstName = firstNameVar, LastName = lastNameVar, Address = new AddressOptions { City = cityVar, Country = "AU", PostalCode = postalCodeVar, Line1 = addressLine1Var, Line2 = addressLine2Var, State = statesPickerVar }, Dob = new AccountDobOptions { Day = dobDayVar, Month = dobMonthVar, Year = dobYearVar }, Type = "individual", Verification = verifiy, PhoneNumber = "+611234567"//Convert.ToString(Xamarin.Forms.Application.Current.Properties["phoneNumber"]) }; //--------Create Payout Account-----------// var options = new AccountCreateOptions { Email = "*****@*****.**", Type = AccountType.Custom, Country = "AU", LegalEntity = legalEntity }; var services = new AccountService(); Account account = services.Create(options); //---------Create External Bank Account and return Token---------/// TokenCreateOptions optionss = new TokenCreateOptions { BankAccount = new BankAccountOptions { Country = "AU", AccountNumber = accountNumberVar, RoutingNumber = routingNumberVar, Currency = "aud" } }; TokenService service = new TokenService(); Token stripeToken = service.Create(optionss); var externalOption = new ExternalAccountCreateOptions { ExternalAccountTokenId = stripeToken.Id, //pass the bank account creation token }; var externalAccount = new ExternalAccountService(); var bankAccount = externalAccount.Create(account.Id, externalOption); //Bank Account Created // await DisplayAlert("", "" + account.Id, "Ok"); //api.AcceptedStripeAgreement(account.Id,CurrentTimeMillis(), MyIp); //Accepted Stripe TOS await DisplayAlert("", "" + account.Id, "Ok"); }catch (Exception ex) { await DisplayAlert("", "" + ex, "Ok"); } }
public ResponseBussiness <PagoServiciosResponse> ObtenerOpcionesPagoServicios(InfoElementosRequest request) { TokenDto token = new TokenService().Get(); return(new AdministracionPagoServiciosBusiness(token).OpcionesAdicionales(request)); }
public ResponseBussiness <AltaClientesResponse> AltaClientes(AltaClienteRequest altaClienteRequest) { TokenDto token = new TokenService().Get(); return(new ClientesBusiness(token).AltaClientes(altaClienteRequest)); }
public void Setup() { var restClient = new WorldpayRestClient(Configuration.ServiceKey); _authService = restClient.GetAuthService(); _tokenService = restClient.GetTokenService(); }
public ResponseBussiness <List <ConsultaValeFinlagResult> > ConsultaMovimientos(ConsultaMovientoPDVRequest clienteFinlagRequest) { TokenDto token = new TokenService().Get(); return(new FinlagBusiness(token).ConsultarMovimientos(clienteFinlagRequest)); }
private async void Plati_OnClicked(object sender, EventArgs e) { StripeConfiguration.SetApiKey("sk_test_51GwRr9KfuyQgAyDyOUzHiF1oewChAjkEf71ntZvZmSfXKnwnSkOX50nI8bhVLUVEpr7nkymSZ8WEoGy262QzyoR000aqsUZgkZ"); Token stripeToken = null; try { var tokenOprions = new TokenCreateOptions() { Card = new TokenCardOptions() { Number = CreditCardNumber.Text, ExpMonth = Convert.ToInt64(CreditCardExpMonth.Text), ExpYear = Convert.ToInt64(CreditCardExpYear.Text), Cvc = CreditCardSecurityCode.Text } }; var tokenService = new TokenService(); stripeToken = tokenService.Create(tokenOprions); var clan = await _clanService.GetById <Model.Clanovi>(APIServices.ClanId); var customer = new CustomerCreateOptions { Description = "Naplata za kupca", Name = clan.ImePrezime, Source = stripeToken.Id }; var customerService = new CustomerService(); var customerResponse = customerService.Create(customer); var options = new ChargeCreateOptions { Amount = (long)model.CijenaSaPopustom * 100, //5000, Currency = "bam", Customer = customerResponse.Id, Description = "Nova uplata", }; var service = new ChargeService(); service.Create(options); PlacanjeClanarineUpsertRequest input = new PlacanjeClanarineUpsertRequest(); input.BrojKartice = CreditCardNumber.Text; input.ExpMonth = Convert.ToInt32(CreditCardExpMonth.Text); input.ExpYear = Convert.ToInt32(CreditCardExpYear.Text); input.SecurityCode = Convert.ToInt32(CreditCardSecurityCode.Text); input.ClanId = APIServices.ClanId; input.TeretanaId = model.Teretana.TeretanaId; input.TipClanarineId = model.TipClanarine.TipClanarineId; input.DatumUplate = DateTime.Now; if (model.TipClanarine.Tip == "Godisnja") { input.DatumIsteka = input.DatumUplate.AddHours(24); } else if (model.TipClanarine.Tip == "Mjesecna") { input.DatumIsteka = input.DatumUplate.AddDays(30); } else { input.DatumIsteka = input.DatumUplate.AddHours(24); } await _PlacanjeclanarineService.Insert <PlacanjeClanarine>(input); await DisplayAlert("Obavijest", "Uspješno ste uplatili članarinu!", "OK"); await Navigation.PushAsync(new TreningPage(model.Teretana)); } catch { await DisplayAlert("Greška!", "Niste unijeli tačne podatke", "OK"); } }
public async Task GetLatestTokenInformation() { var connection = new SqliteConnection("DataSource=:memory"); try { await connection.OpenAsync(); var options = new DbContextOptionsBuilder <WoWTokenContext>() .UseSqlite(connection) .Options; using (var context = new WoWTokenContext(options)) { context.Tokens.RemoveRange(await context.Tokens.ToListAsync()); context.SaveChanges(); var latestToken = new Data.Models.Database.WoWToken() { LastUpdatedTimestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(), Price = 1240000000, Region = "us" }; var beforeLastToken = new Data.Models.Database.WoWToken() { LastUpdatedTimestamp = new DateTimeOffset(DateTime.UtcNow.AddMinutes(-5)).ToUnixTimeSeconds(), Price = 1230000000, Region = "us" }; await context.Database.EnsureCreatedAsync(); await context.Tokens.AddAsync(latestToken); await context.Tokens.AddAsync(beforeLastToken); await context.Tokens.AddAsync(new Data.Models.Database.WoWToken() { LastUpdatedTimestamp = new DateTimeOffset(DateTime.UtcNow.AddMinutes(-10)).ToUnixTimeSeconds(), Price = 2235000000, Region = "eu" }); await context.Tokens.AddAsync(new Data.Models.Database.WoWToken() { LastUpdatedTimestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(), Price = 1235000000, Region = "eu" }); await context.Tokens.AddAsync(new Data.Models.Database.WoWToken() { LastUpdatedTimestamp = new DateTimeOffset(DateTime.UtcNow.AddMinutes(-5)).ToUnixTimeSeconds(), Price = 1255000000, Region = "eu" }); await context.Tokens.AddAsync(new Data.Models.Database.WoWToken() { LastUpdatedTimestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(), Price = 2255000000, Region = "kr" }); await context.SaveChangesAsync(); var tokenService = new TokenService(context); var latestTokenFromDatabase = await tokenService.GetLatestTokenInformationAsync("us"); Assert.AreEqual(latestToken.Price, latestTokenFromDatabase.Price); Assert.AreEqual("us", latestTokenFromDatabase.Region); Assert.AreEqual(latestToken.Price - beforeLastToken.Price, latestTokenFromDatabase.PriceDifference); } } finally { connection.Close(); } }
public void MultipleDynamicServiceTest() { Guid service1Id = Guid.NewGuid(); Guid service2Id = Guid.NewGuid(); Guid token1Id = Guid.NewGuid(); Guid token2Id = Guid.NewGuid(); var cacheRegion = "cacheRegion"; TimeSpan timeSpan = TimeSpan.FromMilliseconds(10); Guid[] serviceIds = new[] { service1Id, service2Id }; var endpoint1 = "/endpoint1"; var endpoint2 = "/endpoint2"; var innerText1 = "Text1"; var innerText2 = "Text2"; var service1Info = new DynamicServiceInfo { Id = service1Id, Endpoint = endpoint1, Timeout = TimeSpan.FromMilliseconds(5), CircuitBreakerInfo = new CircuitBreakerInfo { ExceptionCount = 1 }, Tokens = new[] { new XPathTokenInfo { Id = token1Id, Name = "XPath", XPath = "/content/text()" } } }; var service2Info = new DynamicServiceInfo { Id = service2Id, Endpoint = endpoint2, Timeout = TimeSpan.FromMilliseconds(5), CircuitBreakerInfo = new CircuitBreakerInfo { ExceptionCount = 1 }, Tokens = new[] { new XPathTokenInfo { Id = token2Id, Name = "XPath", XPath = "/content/text()" } } }; var httpClientResponse1 = new HttpClientResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, Response = $"<content>{innerText1}</content>" }; var httpClientResponse2 = new HttpClientResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, Response = $"<content>{innerText2}</content>" }; var cache = Substitute.For <ICache>(); var httpClientWrapper = Substitute.For <IHttpClientWrapper>(); var serviceRepository = Substitute.For <IServiceRepository>(); var taskScheduler = Substitute.For <ITaskScheduler>(); serviceRepository.GetServicesAndTokens(serviceIds).Returns(new[] { service1Info, service2Info }); httpClientWrapper.PostAsync(endpoint1, null, CancellationToken.None).ReturnsForAnyArgs(callInfo => { var endpointArg = callInfo.ArgAt <string>(0); if (endpointArg.Equals(endpoint1)) { return(httpClientResponse1); } if (endpointArg.Equals(endpoint2)) { return(httpClientResponse2); } return(null); }); var tokenService = new TokenService(cache); var dynamicService = new DynamicService(cache, httpClientWrapper, tokenService); var cachedService = new CachedService(cache, httpClientWrapper, tokenService); var staticService = new StaticService(cache, tokenService); var serviceBroker = new ServiceBrokerService(serviceRepository, dynamicService, cachedService, staticService, taskScheduler, cache); ServiceBrokerResponse actual = serviceBroker.CallServices(serviceIds, cacheRegion, timeSpan); Assert.IsNotNull(actual); Assert.IsNotNull(actual.ServiceResponses); Assert.IsTrue(actual.ServiceResponses.Any()); ServiceResponse serviceResponse1 = actual.ServiceResponses.First(); Assert.AreEqual(ServiceResponseStatus.Success, serviceResponse1.Status); Assert.AreEqual(httpClientResponse1.Response, serviceResponse1.Value); Assert.IsNotNull(serviceResponse1.TokenResponses); Assert.IsTrue(serviceResponse1.TokenResponses.Any()); TokenResponse tokenResponse1 = serviceResponse1.TokenResponses.First(); Assert.AreEqual(TokenResponseStatus.Found, tokenResponse1.Status); Assert.AreEqual(innerText1, tokenResponse1.Value); ServiceResponse serviceResponse2 = actual.ServiceResponses.Skip(1).First(); Assert.AreEqual(ServiceResponseStatus.Success, serviceResponse2.Status); Assert.AreEqual(httpClientResponse2.Response, serviceResponse2.Value); Assert.IsNotNull(serviceResponse1.TokenResponses); Assert.IsTrue(serviceResponse1.TokenResponses.Any()); TokenResponse tokenResponse2 = serviceResponse2.TokenResponses.First(); Assert.AreEqual(TokenResponseStatus.Found, tokenResponse2.Status); Assert.AreEqual(innerText2, tokenResponse2.Value); }
public void SingleCachedServiceTest() { Guid serviceId = Guid.NewGuid(); Guid tokenId = Guid.NewGuid(); var cacheRegion = "cacheRegion"; TimeSpan timeSpan = TimeSpan.FromMilliseconds(10); Guid[] serviceIds = new[] { serviceId }; var endpoint = "/"; var innerText = "Text"; var serviceInfo = new CachedServiceInfo { Id = serviceId, Endpoint = endpoint, Timeout = TimeSpan.FromMilliseconds(5), CircuitBreakerInfo = new CircuitBreakerInfo { ExceptionCount = 1 }, Tokens = new[] { new XPathTokenInfo { Id = tokenId, Name = "XPath", XPath = "/content/text()" } } }; var httpClientResponse = new HttpClientResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, Response = $"<content>{innerText}</content>" }; var cache = new CacheMock(); var httpClientWrapper = Substitute.For <IHttpClientWrapper>(); var serviceRepository = Substitute.For <IServiceRepository>(); var taskScheduler = Substitute.For <ITaskScheduler>(); serviceRepository.GetServicesAndTokens(serviceIds).Returns(new[] { serviceInfo }); httpClientWrapper.PostAsync(endpoint, null, CancellationToken.None).ReturnsForAnyArgs(httpClientResponse); var tokenService = new TokenService(cache); var dynamicService = new DynamicService(cache, httpClientWrapper, tokenService); var cachedService = new CachedService(cache, httpClientWrapper, tokenService); var staticService = new StaticService(cache, tokenService); var serviceBroker = new ServiceBrokerService(serviceRepository, dynamicService, cachedService, staticService, taskScheduler, cache); ServiceBrokerResponse actual = serviceBroker.CallServices(serviceIds, cacheRegion, timeSpan); serviceBroker.CallServices(serviceIds, cacheRegion, timeSpan); httpClientWrapper.ReceivedWithAnyArgs(1).PostAsync(endpoint, null, CancellationToken.None); Assert.IsNotNull(actual); Assert.IsNotNull(actual.ServiceResponses); Assert.IsTrue(actual.ServiceResponses.Any()); ServiceResponse serviceResponse = actual.ServiceResponses.First(); Assert.AreEqual(ServiceResponseStatus.Success, serviceResponse.Status); Assert.AreEqual(httpClientResponse.Response, serviceResponse.Value); Assert.IsNotNull(serviceResponse.TokenResponses); Assert.IsTrue(serviceResponse.TokenResponses.Any()); TokenResponse tokenResponse = serviceResponse.TokenResponses.First(); Assert.AreEqual(TokenResponseStatus.Found, tokenResponse.Status); Assert.AreEqual(innerText, tokenResponse.Value); }
public static void Init() { if (Inited) { return; } Inited = true; var platformUtilsService = Resolve <IPlatformUtilsService>("platformUtilsService"); var storageService = Resolve <IStorageService>("storageService"); var secureStorageService = Resolve <IStorageService>("secureStorageService"); var cryptoPrimitiveService = Resolve <ICryptoPrimitiveService>("cryptoPrimitiveService"); var i18nService = Resolve <II18nService>("i18nService"); var messagingService = Resolve <IMessagingService>("messagingService"); SearchService searchService = null; var stateService = new StateService(); var cryptoFunctionService = new PclCryptoFunctionService(cryptoPrimitiveService); var cryptoService = new CryptoService(storageService, secureStorageService, cryptoFunctionService); var tokenService = new TokenService(storageService); var apiService = new ApiService(tokenService, platformUtilsService, (bool expired) => Task.FromResult(0)); var appIdService = new AppIdService(storageService); var userService = new UserService(storageService, tokenService); var settingsService = new SettingsService(userService, storageService); var cipherService = new CipherService(cryptoService, userService, settingsService, apiService, storageService, i18nService, () => searchService); var folderService = new FolderService(cryptoService, userService, apiService, storageService, i18nService, cipherService); var collectionService = new CollectionService(cryptoService, userService, storageService, i18nService); searchService = new SearchService(cipherService); var lockService = new LockService(cryptoService, userService, platformUtilsService, storageService, folderService, cipherService, collectionService, searchService, messagingService, null); var syncService = new SyncService(userService, apiService, settingsService, folderService, cipherService, cryptoService, collectionService, storageService, messagingService, () => messagingService.Send("logout")); var passwordGenerationService = new PasswordGenerationService(cryptoService, storageService, cryptoFunctionService); var totpService = new TotpService(storageService, cryptoFunctionService); var authService = new AuthService(cryptoService, apiService, userService, tokenService, appIdService, i18nService, platformUtilsService, messagingService); // TODO: export service var auditService = new AuditService(cryptoFunctionService, apiService); var environmentService = new EnvironmentService(apiService, storageService); var eventService = new EventService(storageService, apiService, userService, cipherService); Register <IStateService>("stateService", stateService); Register <ICryptoFunctionService>("cryptoFunctionService", cryptoFunctionService); Register <ICryptoService>("cryptoService", cryptoService); Register <ITokenService>("tokenService", tokenService); Register <IApiService>("apiService", apiService); Register <IAppIdService>("appIdService", appIdService); Register <IUserService>("userService", userService); Register <ISettingsService>("settingsService", settingsService); Register <ICipherService>("cipherService", cipherService); Register <IFolderService>("folderService", folderService); Register <ICollectionService>("collectionService", collectionService); Register <ISearchService>("searchService", searchService); Register <ISyncService>("syncService", syncService); Register <ILockService>("lockService", lockService); Register <IPasswordGenerationService>("passwordGenerationService", passwordGenerationService); Register <ITotpService>("totpService", totpService); Register <IAuthService>("authService", authService); Register <IAuditService>("auditService", auditService); Register <IEnvironmentService>("environmentService", environmentService); Register <IEventService>("eventService", eventService); }
public ResponseBussiness <ConsultaValeFinlagResult> ConsultaValeFinlag(ConsultaValeFinlagRequest consultaValeFinlagRequest) { TokenDto token = new TokenService().Get(); return(new FinlagBusiness(token).ConsultarVale(consultaValeFinlagRequest)); }
public ResponseBussiness <ConsultaMovientoPDVResult> ConsultaMovimientoPDV(ConsultaMovientoPDVRequest consultaMovientoPDVRequest) { TokenDto token = new TokenService().Get(); return(new ConsultaMovientoPDVResult()); }
public AuthorizeController(IStoredGrantManager handleManager, IAuthorizationServerConfiguration config, TokenService tokenService) { _handleManager = handleManager; _config = config; _tokenService = tokenService; }
public AccountController(UserManager <AppUser> userManager, SignInManager <AppUser> signinManager, TokenService tokenService) { this._tokenService = tokenService; this._signinManager = signinManager; this._userManager = userManager; }
public ActionResult ResetPassword(ResetPasswordViewModel model, string returnUrl = "") { if (!ModelState.IsValid) { Notify("The supplied information is invalid. Please try again.", NotificationType.Error); return(ResetPassword(model.UID, returnUrl)); } // Token is available? if (model?.UID == null) { Notify("The supplied information is invalid. Please try again.", NotificationType.Error); return(ResetPassword(model.UID, returnUrl)); } User user; using (UserService uservice = new UserService()) using (TokenService tservice = new TokenService()) using (TransactionScope scope = new TransactionScope()) { // Token is valid? if (!tservice.Exist(model.UID, DateTime.Now)) { Notify("The supplied token is no longer valid. Please try again.", NotificationType.Error); return(ResetPassword(model.UID, returnUrl)); } // Password mismatch? if (!string.Equals(model.Password, model.ConfirmPassword, StringComparison.CurrentCulture)) { Notify("Password combination does not match. Please try again.", NotificationType.Error); return(View(model)); } Token t = tservice.GetByUid(model.UID); user = uservice.GetById(t.UserId); t.Status = ( int )Status.Inactive; //user.Reset = false; user.PasswordDate = DateTime.Now; user.Password = uservice.GetSha1Md5String(model.Password); tservice.Update(t); uservice.Update(user); scope.Complete(); } Notify("Your password was successfully updated. You can proceed and login below.", NotificationType.Success); return(Login(new LoginViewModel() { Password = model.Password, ReturnUrl = returnUrl, UserName = user.Email }, returnUrl)); }
public void Load (XmlReader xmlReader) { XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader (xmlReader); string ns = Constants.WsidNamespace; reader.MoveToContent (); reader.ReadStartElement ("RoamingStore", ns); reader.MoveToContent (); reader.ReadStartElement ("RoamingInformationCard", ns); reader.MoveToContent (); lang = reader.GetAttribute ("xml:lang"); // metadata reader.ReadStartElement ("InformationCardMetaData", ns); reader.MoveToContent (); reader.ReadStartElement ("InformationCardReference", ns); reader.MoveToContent (); id = reader.ReadElementContentAsString ("CardId", ns); reader.MoveToContent (); version = reader.ReadElementContentAsString ("CardVersion", ns); reader.MoveToContent (); reader.ReadEndElement (); reader.MoveToContent (); name = reader.ReadElementContentAsString ("CardName", ns); reader.MoveToContent (); image_mime = reader.GetAttribute ("MimeType"); image = Convert.FromBase64String ( reader.ReadElementContentAsString ("CardImage", ns)); reader.MoveToContent (); issuer = new Uri ( reader.ReadElementContentAsString ("Issuer", ns)); reader.MoveToContent (); issued = XmlConvert.ToDateTime ( reader.ReadElementContentAsString ("TimeIssued", ns), XmlDateTimeSerializationMode.Utc); reader.MoveToContent (); expires = XmlConvert.ToDateTime ( reader.ReadElementContentAsString ("TimeExpires", ns), XmlDateTimeSerializationMode.Utc); reader.MoveToContent (); if (reader.IsStartElement ("TokenServiceList", ns)) { reader.ReadStartElement ("TokenServiceList", ns); reader.MoveToContent (); for (reader.MoveToContent (); reader.NodeType == XmlNodeType.Element; reader.MoveToContent ()) { reader.ReadStartElement ("TokenService", ns); reader.MoveToContent (); TokenService ts = new TokenService (); ts.ReadXml (reader); token_services.Add (ts); reader.MoveToContent (); reader.ReadEndElement (); } reader.ReadEndElement (); } reader.MoveToContent (); reader.ReadStartElement ("SupportedTokenTypeList", ns); for (reader.MoveToContent (); reader.NodeType == XmlNodeType.Element; reader.MoveToContent ()) supported_token_types.Add (new Uri ( reader.ReadElementContentAsString ("TokenType", Constants.WstNamespace))); reader.ReadEndElement (); reader.MoveToContent (); reader.ReadStartElement ("SupportedClaimTypeList", ns); for (reader.MoveToContent (); reader.NodeType == XmlNodeType.Element; reader.MoveToContent ()) { string uri = reader.GetAttribute ("Uri"); reader.ReadStartElement ("SupportedClaimType", ns); string tag = reader.ReadElementContentAsString ("DisplayTag", ns); reader.MoveToContent (); string desc = reader.ReadElementContentAsString ("Description", ns); reader.MoveToContent (); reader.ReadEndElement (); supported_claim_types.Add (new ClaimTypeDefinition (uri, tag, desc)); } reader.ReadEndElement (); reader.MoveToContent (); self_issued = reader.ReadElementContentAsBoolean ("IsSelfIssued", ns); reader.MoveToContent (); hash_salt = Convert.FromBase64String ( reader.ReadElementContentAsString ("HashSalt", ns)); reader.MoveToContent (); last_updated = XmlConvert.ToDateTime ( reader.ReadElementContentAsString ("TimeLastUpdated", ns), XmlDateTimeSerializationMode.Utc); reader.MoveToContent (); issuer_id = reader.ReadElementContentAsString ("IssuerId", ns); reader.MoveToContent (); issuer_name = reader.ReadElementContentAsString ("IssuerName", ns); reader.MoveToContent (); back_color = reader.ReadElementContentAsInt ("BackgroundColor", ns); reader.MoveToContent (); reader.ReadEndElement (); // InformationCardMetaData // private data reader.MoveToContent (); reader.ReadStartElement ("InformationCardPrivateData", ns); reader.MoveToContent (); master_key = Convert.FromBase64String ( reader.ReadElementContentAsString ("MasterKey", ns)); reader.MoveToContent (); if (reader.IsStartElement ("ClaimValueList", ns)) { reader.ReadStartElement ("ClaimValueList", ns); reader.MoveToContent (); for (reader.MoveToContent (); reader.NodeType == XmlNodeType.Element; reader.MoveToContent ()) { string uri = reader.GetAttribute ("Uri"); reader.ReadStartElement ("ClaimValue", ns); reader.MoveToContent (); string value = reader.ReadElementContentAsString ("Value", ns); reader.MoveToContent (); reader.ReadEndElement (); claim_values.Add (new ClaimValue (uri, value)); } reader.ReadEndElement (); reader.MoveToContent (); } reader.ReadEndElement (); // InformationCardPrivateData reader.MoveToContent (); reader.ReadEndElement (); reader.MoveToContent (); reader.ReadEndElement (); }
public TraceController(ITraceStatService stat, IAppDayStatService appStat, TokenService appService) { _stat = stat; _appStat = appStat; _service = appService; }
public ResponseBussiness <ClienteResponse[]> BusquedaCliente(ClienteRequest clienteRequest) { TokenDto token = new TokenService().Get(); return(new ClientesBusiness(token).BusquedaClientes(clienteRequest)); }
public AccountController(DataContext context, TokenService tokenService) { this.context = context; this.tokenService = tokenService; }
public ResponseBussiness <BusquedaMayoristaResponse> BusquedaMayorista(BusquedaMayoristaRequest request) { TokenDto token = new TokenService().Get(); return(new MayoristasBusiness(token).BusquedaMayorista(request)); }
public StripePaymentClient(string apiKey) { _tokenService = new TokenService(_client = new StripeClient(apiKey: apiKey)); _subscriptionService = new SubscriptionService(_client); _customerService = new CustomerService(_client); }
public ResponseBussiness <CuponRedimirResponse> ValidarCupon(ValidarCuponRequest request) { TokenDto token = new TokenService().Get(); return(new CuponesRedimirBusiness(token).SaldoRedimir(request)); }
public AuthController() { _authService = new AuthService(); _tokenService = new TokenService(); }
/// <summary> /// 取得列表 /// </summary> /// <param name="token">查詢者代碼</param> /// <param name="id">活動代號</param> /// <param name="strAccess">APPJsonStr</param> /// <param name="circleKey">學習圈代碼</param> /// <param name="rows">查詢數量</param> /// <param name="pages">查詢索引</param> /// <returns></returns> public IHttpActionResult Get(string strAccess = "", Guid?token = null, int?id = 3, string circleKey = "", int?rows = null, int?pages = 1) { //APP 呼叫 if (strAccess != "") { var requestData = JsonConvert.DeserializeObject <Infrastructure.ViewModel.ActivityFunction.ActivityListRequest>(strAccess); if (requestData.Account == null || requestData.CircleKey == null || requestData.ICanToken == null || (!requestData.Id.HasValue)) { var response = new Infrastructure.ViewModel.Base.BaseResponse <string>(); response.Success = false; response.Message = "遺漏參數"; response.Data = null; response.State = Infrastructure.ViewModel.Base.LogState.RequestDataError; return(Content(HttpStatusCode.BadRequest, response)); } id = (int)requestData.Id.Value; token = Guid.Parse(requestData.ICanToken); circleKey = requestData.CircleKey; pages = requestData.Pages.HasValue ? requestData.Pages : 1; rows = requestData.Rows.HasValue ? requestData.Rows : 20; } tokenService = new TokenService(); switch (id.Value) { //查詢主題討論的列表 case (int)activityEnum.Discussion: discussionService = new DiscussionService(); var discussionResponse = new Infrastructure.ViewModel.Base.ResultBaseModel <Infrastructure.ViewModel.ActivityFunction.Discussion.DiscussionModuleList>(); var discussionData = discussionService.GetDiscussionList(circleKey, pages, rows); if (discussionData != null && discussionData.FirstOrDefault() != null) { discussionResponse.Data = discussionData.ToArray(); discussionResponse.Success = true; return(Ok(discussionResponse)); } else { discussionResponse.Data = new Infrastructure.ViewModel.ActivityFunction.Discussion.DiscussionModuleList[0]; discussionResponse.Success = true; discussionResponse.Message = "查無資料"; return(Ok(discussionResponse)); } case (int)activityEnum.SignIn: try { var checkMember = tokenService.GetTokenInfo(token.Value.ToString()).Result; var signInResponse = new Infrastructure.ViewModel.Base.ResultBaseModel <Infrastructure.ViewModel.ActivityFunction.SignIn.SignInModuleList>(); signInService = new SignInService(); var signIndata = signInService.GetSignInList(checkMember.MemberId, circleKey, pages, rows); if (signIndata.FirstOrDefault() != null) { signInResponse.Data = signIndata.ToArray(); signInResponse.Success = true; signInResponse.Message = "查詢成功"; return(Ok(signInResponse)); } else { signInResponse.Success = true; signInResponse.Message = "查無資料"; signInResponse.Data = new Infrastructure.ViewModel.ActivityFunction.SignIn.SignInModuleList[0]; return(Ok(signInResponse)); } } catch (Exception ex) { return(Ok(ex.Message)); } case (int)activityEnum.Vote: var voteService = new VoteService(); var voteList = voteService.GetList(circleKey); var voteResponse = new Infrastructure.ViewModel.Base.ResultBaseModel <Infrastructure.ViewModel.ActivityFunction.Vote.VoteListResponse>(); if (voteList == null) { voteResponse.Message = "無資料"; } else { voteResponse.Message = "查詢成功"; voteResponse.Data = voteList.ToArray(); } voteResponse.Success = true; return(Ok(voteResponse)); case (int)activityEnum.Material: var materialService = new MaterialService(); try { var materialList = new List <MaterialViewModel>(); if (pages.HasValue && rows.HasValue) { materialList = materialService.GetFiles(circleKey, pages.Value, rows.Value); } else { materialList = materialService.GetFiles(circleKey); } var materialResponse = new Infrastructure.ViewModel.Base.ResultBaseModel <MaterialViewModel>(); if (materialList == null) { materialResponse.Message = "無資料"; } else { materialResponse.Message = "查詢成功"; materialResponse.Data = materialList.ToArray(); } materialResponse.Success = true; return(Ok(materialResponse)); } catch (Exception ex) { return(Ok(ex.Message)); } default: return(Content(HttpStatusCode.InternalServerError, "錯誤的查詢")); } }
private async void Client_SendingRequest(System.Net.Http.HttpClient client, string resource) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await TokenService.AquireAADToken(resource)); }
public AccountController(DataContext context, TokenService tokenService) { _tokenService = tokenService; _context = context; }
public IActionResult Subscription(CustomerPaymentViewModel payment) { string email = HttpContext.Session.GetString("User"); ViewBag.isLoggedIn = 1; try { NewWebSubContext context = HttpContext.RequestServices.GetService(typeof(new_websub.NewWebSubContext)) as NewWebSubContext; string query = "select * from useraccounts u inner join address a on u.AddressId=a.addresskey where u.Email=@Email"; MySqlConnection conn = context.GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand(query, conn); MySqlParameter param = new MySqlParameter("@Email", email); param.MySqlDbType = MySqlDbType.VarChar; cmd.Parameters.Add(param); MySqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { User user = new User(); user.Email = email; user.Id = reader["UserID"].ToString(); user.FullName = reader["UserName"].ToString(); user.StripeCustomerId = ""; user.AddressLine1 = reader["Address1"].ToString(); user.AddressLine2 = reader["Address2"].ToString(); user.City = reader["City"].ToString(); user.State = reader["State"].ToString(); user.Zip = reader["Zipcode"].ToString(); user.Country = reader["Country"].ToString(); user.HistoryView = true; StripeConfiguration.SetApiKey(_stripeSettings.Value.SecretKey); var tokenoptions = new TokenCreateOptions { Card = new CreditCardOptions { Number = payment.CardNumber, ExpYear = payment.ExpiryYear, ExpMonth = payment.ExpiryMonth, Cvc = payment.Cvc } }; var tokenservice = new TokenService(); Token stripeToken = tokenservice.Create(tokenoptions); payment.cardtoken = stripeToken.Id; CustomerCreateOptions customerCreateOptions = GetCustomerCreateOptions(payment, user); var cusservice = new CustomerService(); var customers = cusservice.Create(customerCreateOptions); Subscription subscription; var plservice = new PlanService(); try { var plplan = plservice.Get(payment.subsctype); var items = new List <SubscriptionItemOption> { new SubscriptionItemOption { PlanId = plplan.Id } }; var suboptions = new SubscriptionCreateOptions { CustomerId = customers.Id, Items = items }; var subservice = new SubscriptionService(); subscription = subservice.Create(suboptions); } catch { var options = new PlanCreateOptions { Product = new PlanProductCreateOptions { Id = payment.subsctype, Name = payment.subsctype }, Amount = payment.Amount, Currency = payment.Currency, Interval = payment.subsctype, Id = payment.subsctype }; var service = new PlanService(); Plan plan = service.Create(options); var items = new List <SubscriptionItemOption> { new SubscriptionItemOption { PlanId = plan.Id } }; var suboptions = new SubscriptionCreateOptions { CustomerId = customers.Id, Items = items }; var subservice = new SubscriptionService(); subscription = subservice.Create(suboptions); } reader.Close(); // insert into subscriptions table query = "insert into subscriptions(Email, CustomerId, SubscriptionId, Subscription_Started, Subscription_Ended) values(@Email," + "@CustomerId, @SubscriptionId, @Subscription_Started, @Subscription_Ended)"; MySqlCommand cmd1 = new MySqlCommand(query, conn); MySqlParameter param1 = new MySqlParameter("@Email", user.Email); param1.MySqlDbType = MySqlDbType.VarChar; cmd1.Parameters.Add(param1); param1 = new MySqlParameter("@CustomerId", subscription.CustomerId); param1.MySqlDbType = MySqlDbType.VarChar; cmd1.Parameters.Add(param1); param1 = new MySqlParameter("@SubscriptionId", subscription.Id); param1.MySqlDbType = MySqlDbType.VarChar; cmd1.Parameters.Add(param1); param1 = new MySqlParameter("@Subscription_Started", subscription.StartDate); param1.MySqlDbType = MySqlDbType.DateTime; cmd1.Parameters.Add(param1); param1 = new MySqlParameter("@Subscription_Ended", subscription.EndedAt); param1.MySqlDbType = MySqlDbType.DateTime; cmd1.Parameters.Add(param1); cmd1.ExecuteNonQuery(); HttpContext.Session.SetInt32("isLoggedIn", 1); payment.massage = "Payment created successfully"; //return View("Success"); // render Success.cshtml return(View(payment)); } else { return(RedirectToAction(nameof(Login))); } } catch (Exception ex) { MailMessage mail = new MailMessage(); mail.From = new MailAddress(_emailSettings.Value.PrimaryEmail); mail.Subject = "Subscription Fail"; mail.IsBodyHtml = true; mail.Body = ex.Message; mail.Sender = new MailAddress(_emailSettings.Value.PrimaryEmail); mail.To.Add(email); SmtpClient smtp = new SmtpClient(); smtp.Host = _emailSettings.Value.PrimaryDomain; //Or Your SMTP Server Address smtp.Port = _emailSettings.Value.PrimaryPort; smtp.UseDefaultCredentials = false; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Credentials = new System.Net.NetworkCredential(_emailSettings.Value.PrimaryEmail, _emailSettings.Value.PrimaryPassword); //Or your Smtp Email ID and Password smtp.EnableSsl = _emailSettings.Value.EnableSsl; smtp.Send(mail); payment.massage = ex.Message; return(View(payment)); } }
private HttpResponseMessage ProcessRefreshTokenRequest(ValidatedRequest validatedRequest) { Tracing.Information("Processing refresh token request"); var tokenService = new TokenService(_config.GlobalConfiguration); var response = tokenService.CreateTokenResponse(validatedRequest.TokenHandle, _handleManager); return Request.CreateTokenResponse(response); }
private HttpResponseMessage ProcessAuthorizationCodeRequest(ValidatedRequest validatedRequest) { Tracing.Information("Processing authorization code request"); var tokenService = new TokenService(_config.GlobalConfiguration); var response = tokenService.CreateTokenResponse(validatedRequest.StoredGrant, _handleManager); return Request.CreateTokenResponse(response); }
public void SetUp() { mockRepo = new Mock<IRepository<Token>>(); testService = new TokenService(mockRepo.Object); }
private HttpResponseMessage ProcessAssertionGrant(ValidatedRequest validatedRequest) { ClaimsPrincipal principal; try { Tracing.Information("Calling assertion grant handler for assertion: " + validatedRequest.Assertion); principal = _assertionGrantValidator.ValidateAssertion(validatedRequest); } catch (Exception ex) { Tracing.Error("Unhandled exception in assertion grant handler: " + ex.ToString()); throw; } if (principal == null) { Tracing.Error("Assertion grant handler failed to validate assertion"); return Request.CreateOAuthErrorResponse(OAuthConstants.Errors.InvalidGrant); } var sts = new TokenService(_config.GlobalConfiguration); var response = sts.CreateTokenResponse(validatedRequest, principal); return Request.CreateTokenResponse(response); }
public void Init() { DataProtectection.Instance = new NoProtection(); globalConfiguration = new GlobalConfiguration() { Issuer = "Test Issuer" }; rocv = new Mock <IResourceOwnerCredentialValidation>(); config = new Mock <IAuthorizationServerConfiguration>(); handleManager = new Mock <IStoredGrantManager>(); assertionGrantValidator = new Mock <IAssertionGrantValidation>(); clientManager = new Mock <IClientManager>(); tokenService = new TokenService(globalConfiguration); #region Setup Test Client string secret = "12345678"; byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(secret); string base64EncodedSecret = Convert.ToBase64String(encodedByte); _Client = new Client() { ClientId = "MobileAppShop", ClientSecret = base64EncodedSecret, Flow = OAuthFlow.ResourceOwner, AllowRefreshToken = true }; #endregion #region Setup Test Application var scope = new Scope(); scope.Name = "read"; scope.AllowedClients = new List <Client>(); scope.AllowedClients.Add(_Client); _Scopes = new List <Scope>(); _Scopes.Add(scope); string symmetricKey = "C33333333333333333333333335="; byte[] keybytes = Convert.FromBase64String(symmetricKey); SecurityKey securityKey = new InMemorySymmetricSecurityKey(keybytes); _Application = new Application() { Name = "Test Application 1", Scopes = _Scopes, Audience = "Test Audience", TokenLifetime = 1, AllowRefreshToken = true, }; #endregion #region Setup Example StoredGrant Claim[] resourceOwnerClaims = { new Claim("Username", "JohnSmith"), new Claim("sub", "JohnSmith") }; _StoredGrant = new StoredGrant() { GrantId = "MyFavouriteRefrehToken1234", CreateRefreshToken = true, Client = _Client, ResourceOwner = resourceOwnerClaims.ToStoredGrantClaims().ToList(), Expiration = DateTime.Now.AddDays(1), RefreshTokenExpiration = DateTime.Now.AddMonths(1), Type = StoredGrantType.RefreshTokenIdentifier, Scopes = _Scopes, Application = _Application }; #endregion #region Setup Mocking Objects // IAuthorizationServerConfiguration config.Setup(x => x.FindApplication(It.IsNotNull <string>())) .Returns((string name) => { return(_Application); }); config.Setup(x => x.GlobalConfiguration).Returns(() => globalConfiguration); // IClientManager clientManager.Setup(x => x.Get(It.IsNotNull <string>())) .Returns((string clientId) => { return(_Client); }); // IResourceOwnerCredentialValidation rocv.Setup(x => x.Validate(It.IsNotNull <string>(), It.IsNotNull <string>())) .Returns((string username, string password) => { return(Principal.Create("Test", resourceOwnerClaims)); }); // IStoredGrantManager handleManager.Setup(x => x.Get(It.IsNotNull <string>())) .Returns((string grantIdentifier) => { return(_StoredGrant); }); #endregion _TokenController = new TokenController( rocv.Object, config.Object, handleManager.Object, assertionGrantValidator.Object, tokenService, clientManager.Object); _TokenController.Request = new HttpRequestMessage(); _TokenController.Request.SetConfiguration(new HttpConfiguration()); }
public RequireTokenAttribute(bool asAdministrator = false) { this.asAdministrator = asAdministrator; this.tokenService = new TokenService(new EFRepository<Token>(new DatabaseContext())); }
private HttpResponseMessage ProcessResourceOwnerCredentialRequest(ValidatedRequest validatedRequest) { Tracing.Information("Processing resource owner credential request"); ClaimsPrincipal principal; try { principal = _rocv.Validate(validatedRequest.UserName, validatedRequest.Password); } catch (Exception ex) { Tracing.Error("Resource owner credential validation failed: " + ex.ToString()); throw; } if (principal != null && principal.Identity.IsAuthenticated) { var sts = new TokenService(this._config.GlobalConfiguration); var response = sts.CreateTokenResponse(validatedRequest, principal); // check if refresh token is enabled for the client if (validatedRequest.Client.AllowRefreshToken && validatedRequest.Application.AllowRefreshToken) { var handle = StoredGrant.CreateRefreshTokenHandle( principal.GetSubject(), validatedRequest.Client, validatedRequest.Application, principal.Claims, validatedRequest.Scopes, DateTime.UtcNow.AddYears(5)); _handleManager.Add(handle); response.RefreshToken = handle.GrantId; } return Request.CreateTokenResponse(response); } else { return Request.CreateOAuthErrorResponse(OAuthConstants.Errors.InvalidGrant); } }
private async void LoginButton_Click_1(object sender, RoutedEventArgs e) { var stateContainer = StateContainer.GetStateContainer(); string errorMessage = ""; if (stateContainer.registrationStateService.IsLogin) { errorMessage = ValidateLogin(LoginBox.Text, PasswordBox.Password, EmailBox.Text, false); } else { errorMessage = ValidateLogin(LoginBox.Text, PasswordBox.Password, EmailBox.Text, true); } if (!string.IsNullOrEmpty(errorMessage)) { LoginMessageBlock.Text = errorMessage; LoginMessageBlock.Visibility = Visibility.Visible; return; } Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("userName", LoginBox.Text); parameters.Add("password", PasswordBox.Password); if (stateContainer.registrationStateService.IsLogin) { var users = await userProvider.GetAllUsersAsync(); var currentUser = users.FirstOrDefault(x => x.Login == LoginBox.Text && x.Password == HashService.GetHash(PasswordBox.Password)); if (currentUser != null) { var strongKey = await userProvider.GetStrongKeyAsync(currentUser.Id); var session = await userProvider.GetSessionAsync(currentUser.Id); tokenService = new TokenService(currentUser.Id); string acessToken = await tokenService.MakeAuthTokenAsync(currentUser.Id); stateContainer.sessionStateService.SetStateAsync(strongKey: strongKey.Key, clientPrivateKey: session.ClientPrivateKey, clientPublicKey: session.ClientPublicKey, serverPublicKey: session.ServerPublicKey, acessToken: acessToken); ContactsForm contactForm = new ContactsForm(); contactForm.Show(); Close(); } else { var httpRequestMessage = new HttpRequestMessage(); httpRequestMessage.Method = HttpMethod.Post; httpRequestMessage.RequestUri = new Uri(ConfigurationManager.AppSettings.Get("devUrl") + Urls.AuthUrl); var form = new MultipartFormDataContent(); foreach (var parameter in parameters) { form.Add(new StringContent(parameter.Value), parameter.Key); } httpRequestMessage.Content = form; var authResponse = await baseHttpRequest.httpClient.SendAsync(httpRequestMessage); switch (authResponse.StatusCode) { case HttpStatusCode.BadRequest: LoginMessageBlock.Text = "Wrong login or password!"; LoginMessageBlock.Visibility = Visibility.Visible; break; case HttpStatusCode.Unauthorized: LoginMessageBlock.Text = "Wrong login or password!"; LoginMessageBlock.Visibility = Visibility.Visible; break; case HttpStatusCode.InternalServerError: LoginMessageBlock.Text = "Internal server error!"; LoginMessageBlock.Visibility = Visibility.Visible; break; case HttpStatusCode.OK: string content = await authResponse.Content.ReadAsStringAsync(); var authResult = JsonConvert.DeserializeObject <AuthResult>(content); await userProvider.СreateOrUpdateAuthStorageAsync(authResult.UserId, authResult.AccessToken, authResult.RefreshToken); var sessionService = new SessionService(authResult.UserId); await sessionService.MakeSessionAsync(authResult.AccessToken, authResult.RefreshToken); await userProvider.CreateUserAsync(authResult.UserId, LoginBox.Text, HashService.GetHash(PasswordBox.Password)); ContactsForm contactForm = new ContactsForm(); contactForm.Show(); Close(); break; } } } else { var httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(ConfigurationManager.AppSettings.Get("devUrl") + Urls.RegisterUrl); var form = new MultipartFormDataContent(); foreach (var parameter in parameters) { form.Add(new StringContent(parameter.Value), parameter.Key); } httpRequest.Content = form; var registerResult = await baseHttpRequest.httpClient.SendAsync(httpRequest); switch (registerResult.StatusCode) { case HttpStatusCode.OK: string testerToken = ConfigurationManager.AppSettings.Get("testerToken"); var authUserInfo = JsonConvert.DeserializeObject <AuthResult>( await registerResult.Content.ReadAsStringAsync() ); var phoneConfirmRequestMessage = new HttpRequestMessage(); phoneConfirmRequestMessage.Method = HttpMethod.Get; phoneConfirmRequestMessage.RequestUri = new Uri(ConfigurationManager.AppSettings.Get("devUrl") + $"{Urls.ConfirmPhoneTestUrl}/{authUserInfo.UserId}"); phoneConfirmRequestMessage.Headers.Add("TesterToken", testerToken); var phoneConfirmResult = await baseHttpRequest.httpClient.SendAsync(phoneConfirmRequestMessage); if (phoneConfirmResult.StatusCode == HttpStatusCode.OK) { var sessionService = new SessionService(authUserInfo.UserId); await userProvider.СreateOrUpdateAuthStorageAsync(authUserInfo.UserId, authUserInfo.AccessToken, authUserInfo.RefreshToken); await sessionService.MakeSessionAsync(authUserInfo.AccessToken, authUserInfo.RefreshToken); await userProvider.CreateUserAsync(authUserInfo.UserId, LoginBox.Text, HashService.GetHash(PasswordBox.Password)); ContactsForm contact = new ContactsForm(); contact.Show(); Close(); } else { MessageBox.Show($"Something was error"); } break; case HttpStatusCode.BadRequest: break; case HttpStatusCode.InternalServerError: break; } } //LoginMessageBlock.Text = "Wrong login or password!"; //LoginMessageBlock.Visibility = Visibility.Visible; }
private ActionResult PerformImplicitGrant(ValidatedRequest validatedRequest) { Tracing.Information("Performing implict grant"); var sts = new TokenService(this._config.GlobalConfiguration); var response = sts.CreateTokenResponse(validatedRequest, ClaimsPrincipal.Current); var tokenString = string.Format("access_token={0}&token_type={1}&expires_in={2}", response.AccessToken, response.TokenType, response.ExpiresIn); if (!string.IsNullOrWhiteSpace(validatedRequest.State)) { tokenString = string.Format("{0}&state={1}", tokenString, Server.UrlEncode(validatedRequest.State)); } var redirectString = string.Format("{0}#{1}", validatedRequest.RedirectUri.Uri, tokenString); Tracing.Information("Sending token response to redirect URI"); return Redirect(redirectString); }
public static void Init(string customUserAgent = null, string clearCipherCacheKey = null, string[] allClearCipherCacheKeys = null) { if (Inited) { return; } Inited = true; var platformUtilsService = Resolve <IPlatformUtilsService>("platformUtilsService"); var storageService = Resolve <IStorageService>("storageService"); var secureStorageService = Resolve <IStorageService>("secureStorageService"); var cryptoPrimitiveService = Resolve <ICryptoPrimitiveService>("cryptoPrimitiveService"); var i18nService = Resolve <II18nService>("i18nService"); var messagingService = Resolve <IMessagingService>("messagingService"); SearchService searchService = null; var stateService = new StateService(); var cryptoFunctionService = new PclCryptoFunctionService(cryptoPrimitiveService); var cryptoService = new CryptoService(storageService, secureStorageService, cryptoFunctionService); var tokenService = new TokenService(storageService); var apiService = new ApiService(tokenService, platformUtilsService, (bool expired) => { messagingService.Send("logout", expired); return(Task.FromResult(0)); }, customUserAgent); var appIdService = new AppIdService(storageService); var userService = new UserService(storageService, tokenService); var settingsService = new SettingsService(userService, storageService); var cipherService = new CipherService(cryptoService, userService, settingsService, apiService, storageService, i18nService, () => searchService, clearCipherCacheKey, allClearCipherCacheKeys); var folderService = new FolderService(cryptoService, userService, apiService, storageService, i18nService, cipherService); var collectionService = new CollectionService(cryptoService, userService, storageService, i18nService); var sendService = new SendService(cryptoService, userService, apiService, storageService, i18nService, cryptoFunctionService); searchService = new SearchService(cipherService, sendService); var vaultTimeoutService = new VaultTimeoutService(cryptoService, userService, platformUtilsService, storageService, folderService, cipherService, collectionService, searchService, messagingService, tokenService, null, (expired) => { messagingService.Send("logout", expired); return(Task.FromResult(0)); }); var policyService = new PolicyService(storageService, userService); var syncService = new SyncService(userService, apiService, settingsService, folderService, cipherService, cryptoService, collectionService, storageService, messagingService, policyService, sendService, (bool expired) => { messagingService.Send("logout", expired); return(Task.FromResult(0)); }); var passwordGenerationService = new PasswordGenerationService(cryptoService, storageService, cryptoFunctionService, policyService); var totpService = new TotpService(storageService, cryptoFunctionService); var authService = new AuthService(cryptoService, apiService, userService, tokenService, appIdService, i18nService, platformUtilsService, messagingService, vaultTimeoutService); var exportService = new ExportService(folderService, cipherService); var auditService = new AuditService(cryptoFunctionService, apiService); var environmentService = new EnvironmentService(apiService, storageService); var eventService = new EventService(storageService, apiService, userService, cipherService); Register <IStateService>("stateService", stateService); Register <ICryptoFunctionService>("cryptoFunctionService", cryptoFunctionService); Register <ICryptoService>("cryptoService", cryptoService); Register <ITokenService>("tokenService", tokenService); Register <IApiService>("apiService", apiService); Register <IAppIdService>("appIdService", appIdService); Register <IUserService>("userService", userService); Register <ISettingsService>("settingsService", settingsService); Register <ICipherService>("cipherService", cipherService); Register <IFolderService>("folderService", folderService); Register <ICollectionService>("collectionService", collectionService); Register <ISendService>("sendService", sendService); Register <ISearchService>("searchService", searchService); Register <IPolicyService>("policyService", policyService); Register <ISyncService>("syncService", syncService); Register <IVaultTimeoutService>("vaultTimeoutService", vaultTimeoutService); Register <IPasswordGenerationService>("passwordGenerationService", passwordGenerationService); Register <ITotpService>("totpService", totpService); Register <IAuthService>("authService", authService); Register <IExportService>("exportService", exportService); Register <IAuditService>("auditService", auditService); Register <IEnvironmentService>("environmentService", environmentService); Register <IEventService>("eventService", eventService); }
public AccountController(UserManager <User> userManager, SignInManager <User> signInManager, TokenService tokenService) { _tokenService = tokenService; _signInManager = signInManager; _userManager = userManager; }
private void Main_Load(object sender, EventArgs e) { if (Settings.Default.LastFormWasMaximized) { WindowState = FormWindowState.Maximized; } else { if (Settings.Default.LastFormHeight > 0) { Height = Settings.Default.LastFormHeight; } if (Settings.Default.LastFormWidth > 0) { Width = Settings.Default.LastFormWidth; } } _profileService = ProfileService.Init(); _tokenService = new TokenService(); toggleConfigurationGroup(false); toggleProfileButtons(false); loadProfiles(); }