/// <summary> /// Generate auth token for the user /// use Password to encrypt the new generated token /// </summary> /// <param name="authTokenRequest">phone , password</param> /// <returns> return AuthTokenResponse(validation errors + token string)</returns> public AuthTokenResponse GenerateAuthToken(AuthTokenRequest authTokenRequest) { var result = new AuthTokenResponse(); var error = ValidateRequest(authTokenRequest); if (error.HasErrors) { result.Errors = error; return(result); } var createdAt = DateTime.UtcNow; var authTokenRow = new DTO.AuthToken(); authTokenRow.Password = authTokenRequest.Password; authTokenRow.Phone = authTokenRequest.Phone; authTokenRow.ExpireAt = createdAt.AddHours(1); authTokenRow.Token = GenerateToken(authTokenRequest.Password, createdAt); _authTokenRepository.Add(authTokenRow); result.Token = authTokenRow.Token; return(result); }
public static TokenFactory GetAccessTokenFactory( [NotNull] this RsdnApiAuthenticator authenticator, [NotNull] string login, [NotNull] string password) { Code.NotNull(authenticator, nameof(authenticator)); AuthTokenResponse token = null; var tokenLock = new AsyncLock(); return(async ct => { if (token != null && token.ExpiresOn >= DateTimeOffset.UtcNow) { return token.AccessToken; } using (await tokenLock.AcquireAsync(ct)) if (token == null || token.ExpiresOn < DateTimeOffset.UtcNow) { token = token == null ? await authenticator.GetTokenByPasswordAsync(login, password, ct) : await authenticator.RefreshTokenAsync(token.RefreshToken, ct) ?? await authenticator.GetTokenByPasswordAsync(login, password, ct); } return token.AccessToken; }); }
public AmadeusAPIServiceClient(System.Net.Http.HttpClient httpClient, IConfiguration configuration) { _config = configuration; DurationOfCache = (_config.GetSection("Variables").GetValue <string>("DurationOfCache")); var nvc = new List <KeyValuePair <string?, string?> >(); nvc.Add(new KeyValuePair <string?, string?>("grant_type", "client_credentials")); nvc.Add(new KeyValuePair <string?, string?>("client_id", _config.GetSection("Secrets").GetSection("AmadeusData").GetSection("APIKey").Value)); nvc.Add(new KeyValuePair <string?, string?>("client_secret", _config.GetSection("Secrets").GetSection("AmadeusData").GetSection("APISecret").Value)); _httpClient = httpClient; HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, _OAuthTokenURL) { Content = new FormUrlEncodedContent(nvc) }; var res = _httpClient.Send(req); var dataTask = res.Content.ReadAsStringAsync(); var data = Task.FromResult(dataTask); var authData = JsonConvert.DeserializeObject <AuthTokenResponse>(data.Result.Result); _tokenData = authData; _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(_tokenData.token_type, _tokenData.access_token); _settings = new System.Lazy <Newtonsoft.Json.JsonSerializerSettings>(() => { var settings = new Newtonsoft.Json.JsonSerializerSettings(); UpdateJsonSerializerSettings(settings); return(settings); }); }
public AccountInfoResponse GetAccountInfo(AuthTokenResponse token) { var client = new WebClient(); client.Headers.Add("Authorization", token.token_type + " " + token.access_token); var stringData = client.DownloadString(@"https://gateway.ea.com/proxy/identity/pids/me"); return(JsonConvert.DeserializeObject <AccountInfoResponse>(stringData)); }
public string GetUserInfo([FromBody] AccessTokenRequest request) { var web = new WebClient(); web.Headers.Set("Content-Type", "application/x-www-form-urlencoded"); string body = $"client_id={request.client_id}&client_secret={request.client_secret}&code={request.code}&grant_type={request.grant_type}&redirect_uri={request.redirect_uri}"; AuthTokenResponse authInfo = JsonConvert.DeserializeObject <AuthTokenResponse>(web.UploadString(" https://accounts.spotify.com/api/token", body)); string authToken = authInfo.access_token; SpotifyUserInfo userInfo = JsonConvert.DeserializeObject <SpotifyUserInfo>(GetUserId(authToken)); userInfo.authToken = authToken; return(JsonConvert.SerializeObject(userInfo)); }
/// <summary> /// Get usersId for achievement database. /// </summary> /// <param name="token"></param> /// <returns></returns> internal string GetPersonas(AuthTokenResponse token) { var client = new WebClient { Encoding = Encoding.UTF8 }; var userId = originAPI.GetAccountInfo(originAPI.GetAccessToken()).pid.pidId; var url = string.Format(@"https://gateway.ea.com/proxy/identity/pids/{0}/personas?namespaceName=cem_ea_id", userId); client.Headers.Add("Authorization", token.token_type + " " + token.access_token); var stringData = client.DownloadString(url); JObject objectData = JObject.Parse(stringData); return(((string)objectData["personas"]["personaUri"][0]).Replace("/pids/" + userId + "/personas/", "")); }
public void SetCurrentToken(AuthTokenResponse token) { var id = _varsService.GetVar(_currentAccountVar); if (id == null) { return; } using var db = _dbFactory(); var col = GetAccountsCol(db); var account = col.Find(a => a.ID == int.Parse(id)).First(); var salt = GenerateSalt(); account.Salt = Convert.ToBase64String(salt); account.EncryptedToken = EncryptToken(token, salt); col.Update(account); }
public UsageResponse GetUsage(long userId, string gameId, AuthTokenResponse token) { var gameStoreData = OriginApiClient.GetGameStoreData(gameId); string multiplayerId = gameStoreData.platforms.First(a => a.platform == "PCWIN").multiplayerId; string masterTitleId = gameStoreData.masterTitleId; var client = new WebClient(); client.Headers.Add("authtoken", token.access_token); client.Headers.Add("X-Origin-Platform", "PCWIN"); if (!string.IsNullOrEmpty(multiplayerId)) { client.Headers.Add("MultiplayerId", multiplayerId); } var stringData = client.DownloadString(string.Format(@"https://api1.origin.com/atom/users/{0}/games/{1}/usage", userId, masterTitleId)); return(new UsageResponse(stringData)); }
public void AddOrUpdateAccount(Account account, AuthTokenResponse token, bool asCurrent = true) { Code.NotNull(account, nameof(account)); using var db = _dbFactory(); var col = GetAccountsCol(db); //col.EnsureIndex(a => a.ID, true); var salt = GenerateSalt(); col.Upsert(new AccountData { ID = account.ID, Account = account, EncryptedToken = EncryptToken(token, salt), Salt = Convert.ToBase64String(salt) }); if (asCurrent) { _varsService.SetVar(_currentAccountVar, account.ID.ToString()); } }
public ApiConnectionService(AccountsService accountsService) { _accountsService = accountsService; _authenticator = RsdnClientHelpers.CreateAuthenticator( //new Uri("https://localhost:44389"), _rsdnUri, "test_public_client", "", "offline_access"); _token = _accountsService.GetCurrentToken(); Client = RsdnClientHelpers.CreateClient( _rsdnUri, _authenticator.GetAccessTokenFactory( () => _token, token => { accountsService.SetCurrentToken(token); _token = token; })); }
private AuthTokenResponse GenerateToken() { using (HttpClient apiHost = new HttpClient()) { //set base address apiHost.BaseAddress = new Uri(destinationConfig.TokenGeneratorConfig.TokenGeneratorApiBaseUrl); //set headers var idAndSecret = string.Format("{0}:{1}", destinationConfig.TokenGeneratorConfig.ClientId, destinationConfig.TokenGeneratorConfig.ClientSecret); var encodedAuthorization = Convert.ToBase64String(Encoding.UTF8.GetBytes(idAndSecret)); apiHost.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encodedAuthorization); apiHost.DefaultRequestHeaders.Add("Cookie", "recaptchaVerified=true"); //derive input param dictionary to pass Dictionary <string, string> inputParams = new Dictionary <string, string>(); inputParams.Add("grant_type", destinationConfig.TokenGeneratorConfig.GrantType); inputParams.Add("scope", destinationConfig.TokenGeneratorConfig.Scope); inputParams.Add("username", destinationConfig.TokenGeneratorConfig.UserName); inputParams.Add("password", destinationConfig.TokenGeneratorConfig.Password); HttpContent content = new FormUrlEncodedContent(inputParams); //call API var apiResponse = apiHost.PostAsync("identity/connect/token", content).Result; string responseString = apiResponse.Content.ReadAsStringAsync().Result; if (apiResponse.IsSuccessStatusCode) { _AuthToken = apiResponse.Content.ReadAsAsync <AuthTokenResponse>().Result; } else { throw new CmiException(string.Format("Token could not be generated!!!{0}Response: {1}", Environment.NewLine, responseString)); } } return(_AuthToken); }
public static TokenFactory GetAccessTokenFactory( [NotNull] this RsdnApiAuthenticator authenticator, [NotNull] CodeFlowData flowData, [NotNull] IDictionary <string, string> redirectParams) { Code.NotNull(authenticator, nameof(authenticator)); Code.NotNull(flowData, nameof(flowData)); Code.NotNull(redirectParams, nameof(redirectParams)); AuthTokenResponse token = null; var tokenLock = new AsyncLock(); return(async ct => { if (token == null) { using (await tokenLock.AcquireAsync(ct)) if (token == null) { token = await authenticator.GetTokenByCodeAsync(flowData, redirectParams, ct); return token.AccessToken; } } if (token.ExpiresOn >= DateTimeOffset.UtcNow) { return token.AccessToken; } using (await tokenLock.AcquireAsync()) if (token.ExpiresOn < DateTimeOffset.UtcNow) { token = await authenticator.RefreshTokenAsync(token.RefreshToken, ct); } return token?.AccessToken; }); }
public void OnAuthorization(AuthorizationFilterContext context) { CallContext.Current.Headers.TryGetValue(Keystore.Headers.AccountId, out string accountId); if (string.IsNullOrEmpty(accountId) == true) { throw Errors.MissingHeader(Keystore.Headers.AccountId); } AuthTokenResponse response = null; try { response = _tokenService.ValidateAndRefreshAsync(accountId).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (BaseApplicationException ex) { //log exception. since we want to override the exception if (ex.ErrorCode.Equals(ErrorCodes.ExpiredToken) || ex.ErrorCode.Equals(ErrorCodes.ValueDoesNotExist)) { throw Errors.InvalidHeader(Keystore.Headers.AccountId); } throw; } catch (Exception ex) { //log exception. since we want to override the exception throw Errors.InternalServerError(); } if (response == null || string.IsNullOrEmpty(response.UserId) == true) { throw Errors.InvalidHeader(Keystore.Headers.AccountId); } CallContext.Current.SetUserId(response.UserId); CallContext.Current.SetToken(response.Token); }
public static async Task <object> HandleWebServ(HttpListenerRequest request) { Console.WriteLine("[LOG] Get Request for: " + request.RawUrl); if (request.RawUrl == ("/authenticate")) { string[] response = { "", "" }; try { string payloader = GetRequestPostData(request); string username = payloader.Split(',')[0].Split('=')[1]; string password = payloader.Split(',')[1].Split('=')[1]; if (DatabaseManager.checkAccount(username, password)) { Dictionary <string, string> data = DatabaseManager.getAccountData(username, password); if (data["banned"] == "1") { Console.WriteLine("Login from: " + username + " but banned."); response[1] = "403"; LQResponse lqRes = new LQResponse() { rate = 0, reason = "account_banned", status = "FAILED", delay = 5000, banned = 7357299742000 }; var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new NullPropertiesConverter() }); response[0] = serializer.Serialize(lqRes); } else { Console.WriteLine("Successful Login from: " + username); response[1] = "200"; LQResponse lqRes = new LQResponse() { rate = 325, reason = "login_rate", status = "LOGIN", lqt = new LQt { account_id = Convert.ToInt64(data["id"]), account_name = username, other = "lMnzmeRQXfuSO7-E8gyIC2njt28aZDiQ3WE2EC55o3m2tnfadjIvDzAmEB4oRyoZfApyQ+HBMbpu5yvY2Wl2XzHKrjp0W-V4", fingerprint = "7823ae2957be6d04243330e71143cf98", signature = "HDNlMYyci+N1GvZlYDqV/38Qco9BIEP+xI3K/trtHqIdv/53XaUR5l03pIQV0K6jiq/XulOYySRRbknr1rq7qMRgTsbTw/quzZ+wTFS9Kz7qIC1Ekkt7+BUsr6C+rBmUXwH137xP9BoxNrCM/pFgxVdDDg38YlzLNKvxK3Q1kE0=", timestamp = Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(DateTime.UtcNow.Date) - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds), partner_token = "eyJraWQiOiJzMSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiI5NzYwNjdlYi05YmEzLTVlZTgtOWI5ZC0wOGJhNzdjZTZlODIiLCJzY3AiOlsib3BlbmlkIl0sImNsbSI6WyJvcGVuaWQiLCJyZ25fTkExIl0sImRhdCI6eyJ1IjoyNDU1MTUxOTYsInIiOiJOQTEifSwiaXNzIjoiaHR0cHM6XC9cL2F1dGgucmlvdGdhbWVzLmNvbSIsImV4cCI6MTUxOTU3OTkwOSwiaWF0IjoxNTE5NTc5MzA5LCJqdGkiOiJsaDRDaC1zWVpqayIsImNpZCI6ImxvbCJ9.PSNqUFQ7kGBIfgxnhYAYCuT0HZ7J7CDhH4XMTeK5CVZBZSHVkihZyljksNYALehilf_S0h56k_GPr5IfeAKhRysgmndcNBDtPALK6ttmvN3ikO83Swb3PjgaDpA1yJUNAVnIN7lcElxoLe_B2W_pYjKoRb3IWQIVSASFHx-zOoI", uuid = "32b79186-bb8a-4f5c-8701-34e94078d2ba", ip = "127.0.0.1", }, delay = 5000, inGameCredentials = new InGameCreds() { user = username, inGame = true, summonerId = 1 } }; var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new NullPropertiesConverter() }); response[0] = serializer.Serialize(lqRes); } } else { Console.WriteLine("Invalid Login from: " + username); response[1] = "200"; LQResponse lqRes = new LQResponse() { rate = 0, reason = "invalid_credentials", status = "FAILED", delay = 5000 }; var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new NullPropertiesConverter() }); response[0] = serializer.Serialize(lqRes); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(response); } else if (request.RawUrl == ("/token")) { string[] response = { "", "" }; AuthTokenResponse atr = new AuthTokenResponse(); try { using (System.IO.Stream body = request.InputStream) // here we have data { using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding)) { string payloader = Uri.UnescapeDataString(reader.ReadToEnd()); atr.access_token = "TUzZDcxYWQxZmYwNTU0ZTg2M2MyMDk5ZmUyZWI2ZQ"; atr.ExpiresIn = 90000; atr.TokenType = "bearer"; atr.Scope = null; response[1] = "200"; response[0] = new JavaScriptSerializer().Serialize(atr);; } } } catch (Exception e) { Console.WriteLine(e.Message); } return(response); } else if (request.RawUrl.StartsWith("/api")) { return(await HandleAPI(request)); } else { string ReadURL = request.RawUrl; if (ReadURL == "/") { ReadURL = "/index.html"; } if (ReadURL == "/favicon.ico") { return(""); } string ContentType = AuthServer.SetContentType(request.RawUrl); string RequestedFile = ReadURL.Split('/').Last(); #if !FILESYSTEM /*using (var db = new LiteEngine("poro.dat")) * { * var file = db.FileStorage.FindById(RequestedFile); * * if (file == null) * return "404"; * * var stream = file.OpenRead(); * * using (var memoryStream = new MemoryStream()) * { * stream.CopyTo(memoryStream); * byte[] bytes = memoryStream.ToArray(); * if (ContentType.StartsWith("image")) * { * return bytes; * } * else * { * return Encoding.Default.GetString(bytes); * } * } * }*/ return("<html><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>LoL Lobby</title><base target=\"_blank\"><link rel=\"stylesheet\" href=\"https://lolstatic-a.akamaihd.net/frontpage/apps/prod/lol_client/de_DE/18f69d3ef970a03a43c86181a3d620f12ac208f6/assets/css/lk3.css\"><script type=\"text/javascript\">var childInterface = {};var spectateDataURL;window.childSandboxBridge = childInterface;if (typeof window.parentSandboxBridge !== \'undefined\') {window.parentSandboxBridge.loaded();window.location.clientAssetPath = window.parentSandboxBridge.clientAssetPath;}spectateDataURL = window.parentSandboxBridge.featuredGamesURL;var locale = \'de_DE\';var versionedAssetPath = \'https://lolstatic-a.akamaihd.net/frontpage/apps/prod/lol_client/de_DE/18f69d3ef970a03a43c86181a3d620f12ac208f6/assets\';var templateVersion = \'18f69d3ef970a03a43c86181a3d620f12ac208f6\';var pagesBasePath = \'https://lolstatic-a.akamaihd.net/frontpage/apps/prod/lol_client/de_DE/18f69d3ef970a03a43c86181a3d620f12ac208f6\';var assetMagickPath = \'https://am-a.akamaihd.net\';/*@TODO: construct templateReferenceBase on the server side, and pass it along with the contextso that the build process can own the definition of how to reference templates.*/var templateReferenceBase = \'lol_client/\' + locale + \'/\' + templateVersion;/*set a default for assetMagickPath, so we don\'t break staging before Harbinger changes get depolyed.*/if (assetMagickPath === \'\') {assetMagickPath = \'https://am-a.akamaihd.net\';}(function() {var rs = document.createElement(\'script\');rs.type = \'text/javascript\';rs.setAttribute(\'data-main\', \'https://lolstatic-a.akamaihd.net/frontpage/apps/prod/lol_client/de_DE/18f69d3ef970a03a43c86181a3d620f12ac208f6/assets/js/main-require.js\');rs.src = window.location.clientAssetPath + \'/htmlTemplates/js/require-2.1.11.min.js\';document.getElementsByTagName(\'head\')[0].appendChild(rs);})();</script><script type=\"text/javascript\">var clientLocale;var clientRegion;var summonerInfo;var gasToken;var accountId;if (typeof window.parentSandboxBridge !== \'undefined\'){clientLocale = window.parentSandboxBridge.locale || \'unknown\';clientRegion = window.parentSandboxBridge.region;if (typeof window.parentSandboxBridge.getSummonerInfo === \'function\') {summonerInfo = window.parentSandboxBridge.getSummonerInfo();gasToken = JSON.parse(summonerInfo.summonerGasToken);accountId = gasToken.pvpnet_account_id;}}window.pCfg = {appname: \'lol_client\',meta: {locale: clientLocale}};if (typeof accountId !== \'undefined\') {pCfg.account = {locale: clientLocale,region: clientRegion,accountId: accountId};}</script></head><body id=\"frontpage\" class=\"i18n-de_DE landing-oembeds\" data-rodeo-concurrency=\"false\" data-lasso-endpoint=\"https://oembed.leagueoflegends.com/oembed\"><div class=\"cbox cbox-r-client\"><div class=\"gsc-fill margin-small\"><div class=\"gsc gsc-fill gsc-gutter-small\"><div class=\"gst w-2-3 h-2-3\"><lasso-embed url=\"http://news-oembed.leagueoflegends.com/v1/euw/de/news/landing-page/uuid/90cf3c12-f005-454e-a8ea-5b3f553a46a8?viewMode=card-tier-1\"></lasso-embed></div><div class=\"gst w-1-3 h-1-3 l-2-3\"><div class=\"gsc gsc-fill gsc-gutter-small\"><div class=\"gst w-1-2 h-1-1\"><div class=\"ct-wr ct-t-store ct-s-card tier-3\" data-ping-meta=\"cardTier=3|cardType=store\"><div class=\"ct-bd\"><img class=\"store-image-portrait\" data-client-image-src=\"/images/champions/Lissandra_3.jpg\" /></div><div class=\"gsc-fill\"><div class=\"overlay pos-bottom\"><h2 class=\"ct-title stacktext\">Programm Lissandra</h2><div class=\"item-cost\"><span class=\"cost-rp\">1350</span></div></div></div><a class=\"gsc-fill action store-unlock\" data-air-navigate-json=\"{"type":"store", "relativeUrl":"/store/tabs/view/skins", "queryString":"showItemId=championsskin_127003" }\" data-analytics-event=\"store:unlock\"></a></div></div><div class=\"gst w-1-2 h-1-1 l-1-2\"><div class=\"ct-wr ct-t-store ct-s-card tier-3\" data-ping-meta=\"cardTier=3|cardType=store\"><div class=\"ct-bd\"><img class=\"store-image-portrait\" data-client-image-src=\"/images/champions/Soraka_6.jpg\" /></div><div class=\"gsc-fill\"><div class=\"overlay pos-bottom\"><h2 class=\"ct-title stacktext\">Programm Soraka</h2><div class=\"item-cost\"><span class=\"cost-rp\">1350</span></div></div></div><a class=\"gsc-fill action store-unlock\" data-air-navigate-json=\"{"type":"store", "relativeUrl":"/store/tabs/view/skins", "queryString":"showItemId=championsskin_16006" }\" data-analytics-event=\"store:unlock\"></a></div></div></div></div><div class=\"gst w-1-3 h-1-3 l-2-3 t-1-3\"><lasso-embed url=\"http://news-oembed.leagueoflegends.com/v1/euw/de/news/landing-page/uuid/44f06393-f567-4481-aea5-9e46d1d533a5?viewMode=card-tier-2\"></lasso-embed></div><div class=\"gst w-1-3 h-1-3 t-2-3\"><lasso-embed url=\"http://news-oembed.leagueoflegends.com/v1/euw/de/news/landing-page/uuid/75dd4c82-e3d1-4211-9689-95edd9c1cf2d?viewMode=card-tier-2\"></lasso-embed></div><div class=\"gst w-1-3 h-1-3 l-1-3 t-2-3\" data-player-survey=\"50\"><lasso-embed url=\"http://news-oembed.leagueoflegends.com/v1/euw/de/news/landing-page/uuid/d93fe2ef-de21-4251-a523-56f46d3c1e0f?viewMode=card-tier-2\"></lasso-embed></div><div class=\"gst w-1-3 h-1-3 l-2-3 t-2-3\"><lasso-embed url=\"http://news-oembed.leagueoflegends.com/v1/euw/de/news/landing-page/uuid/68dcc063-c318-446e-b747-5e68a78d000f?viewMode=card-tier-2\"></lasso-embed></div></div></div></div><script type=\"text/javascript\" src=\"https://lolstatic-a.akamaihd.net/ping/ping-0.1.238.min.js\"></script><script type=\"text/javascript\">(function(){window.addEventListener(\'error\', errorHandler);window.addEventListener(\"load\", function() {var elements = document.getElementsByTagName(\'link\');for (var i = 0; i < elements.length; i++) {var element = elements[i];if (element.rel == \'stylesheet\') {var elementRules = element.sheet.rules;if (elementRules && elementRules.length == 0) {notifyPageError(\'STYLESHEET\', element.href);}}}});function getTargetErrorDescription(element) {if (element.nodeName == \"SCRIPT\") {return element.src;}else {var estr = \"\";for (var p in element) {if (element.hasOwnProperty(p)) {estr += \" | \" + p + \": \" + element[p];}}return estr;}}function errorHandler (err) {notifyPageError(err.target.nodeName, getTargetErrorDescription(err.target));}window.notifyPageError = function notifyPageError(type, message) {/*alert(\'Error: type:\' + type + \' message: \' + message);*/window.ping(\'error\', {\'meta.error_type\': type,\'meta.error_message\': message});}})();</script><script type=\"text/javascript\" src=\"https://lolstatic-a.akamaihd.net/lassojs/0.1.4/lasso.js\"></script><script>(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,\'script\',\'//www.google-analytics.com/analytics.js\',\'ga\');ga(\'create\', \'UA-5859958-26\', \'leagueoflegends.com\');ga(\'send\', \'pageview\');</script></body></html>"); #endif #if FILESYSTEM //Uncomment to create poro.dat /*var x = File.OpenRead(FileURL); * using (var db = new LiteEngine("poro.dat")) * { * var file = db.FileStorage.FindById(RequestedFile); * * if (file == null) * { * db.FileStorage.Upload(RequestedFile, x); * } * }*/ string FileURL = string.Format("app/web{0}", ReadURL); if (ContentType.StartsWith("image")) { return(File.ReadAllBytes(FileURL)); } else { return(File.ReadAllText(FileURL)); } #endif } }
public List <AccountEntitlementsResponse.Entitlement> GetOwnedGames(long userId, AuthTokenResponse token) { var client = new WebClient(); client.Headers.Add("authtoken", token.access_token); client.Headers.Add("accept", "application/vnd.origin.v3+json; x-cache/force-write"); var stringData = client.DownloadString(string.Format(@"https://api1.origin.com/ecommerce2/consolidatedentitlements/{0}?machine_hash=1", userId)); var data = JsonConvert.DeserializeObject <AccountEntitlementsResponse>(stringData); return(data.entitlements); }
async Task <AuthTokenResponse> CreateUser(string userId, UserNamePayload payload) { // ensure we have a user with the given user name var user = await _userRepository.GetByEmailAsync(userId); // generate refresh token var refreshToken = _authService.GenerateRefreshToken(); //await _userRepository.Update(user); Console.WriteLine($"refreshToken: {refreshToken}"); // generate access token if (user != null) { var token = await _authService.Generate(userId); var authTokenResponse = new AuthTokenResponse { AuthToken = token, RefreshToken = refreshToken, UserDbId = user.Id }; var newToken = new DomainLayer.Entities.AuthToken { Auth = authTokenResponse.AuthToken, Refresh = authTokenResponse.RefreshToken, RefreshExpiredAt = DateTime.UtcNow.AddHours(3) }; user.AuthToken = newToken; await _userRepository.Update(user); if (payload.Thumb != null) { user.AvatarPath = payload.Thumb; user.Name = payload.FirstName; await _userRepository.Update(user); } return(authTokenResponse); } else { var authTokenResponse = new AuthTokenResponse { AuthToken = await _authService.Generate(userId), RefreshToken = refreshToken }; var newToken = new DomainLayer.Entities.AuthToken { Auth = authTokenResponse.AuthToken, Refresh = authTokenResponse.RefreshToken, RefreshExpiredAt = DateTime.UtcNow.AddMinutes(15) }; var networks = new List <NetworkProfile> { new NetworkProfile { Link = payload.Network == SocialNetwork.Vk ? $"https://vk.com/id{userId}" : $"https://youtube.com/channel/{payload.ChannalId}", Title = payload.Network == SocialNetwork.Vk ? "VK" : "Youtube", } }; var newUser = new User { AuthToken = newToken, Email = userId, RegistredAt = DateTime.UtcNow, Name = payload.FirstName, Surname = payload.LastName, SocialNetwork = networks, AvatarPath = payload.Thumb }; await _userRepository.AddAsync(newUser); var savedUser = await _userRepository.GetByEmailAsync(userId); authTokenResponse.UserDbId = savedUser.Id; return(authTokenResponse); } }
/// <summary> /// Authenticate request. /// </summary> public AuthTokenResponse Authenticate(AuthTokenRequest request, out string error) { error = null; AuthTokenResponse info = null; var grantType = request.GrantType; if (grantType == "client_credentials") { #region client_credentials var base64ClientId = request.ClientId; var base64ClientSecret = request.ClientSecret; string strClientId = Base64.UrlDecode(base64ClientId); //var clientId = Guid.TryParse(strClientId); //if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) //{ // error = "invalid_grant"; // errorDescription = "username and password are required"; //} //else //{ // var id = sql.Select("ident", "id_id", "id_password", "id_salt"); // id.Where = (SqlColumn)"id_name" == username; // var r = id.Execute(); // if (r.First.Count == 1) // { // var ro = r.First.First; // var spass = ro["id_password"].GetByteArray(); // var ssalt = ro["id_salt"].GetByteArray(); // if (spass == null || ssalt == null) // { // error = "invalid_request"; // errorDescription = "server:spass_ssalt_null"; // } // else // { // var hash = Hash.SHA512(ssalt.Concat(password.ToBytes())); // if (!hash.SequenceEqual(spass)) // { // error = "invalid_grant"; // errorDescription = "invalid username or password"; // } // else // { // info = CreateAuthInfo(ro["id_id"].GetGuid()); // } // } // } // else // { // error = "invalid_grant"; // errorDescription = "invalid username or password"; // } #endregion } else if (string.IsNullOrEmpty(grantType)) { error = "invalid_grant"; } else { error = "unsupported_grant_type"; } return(info); }
public DatabaseResponse AuthenticateAdminUserTokenPermission(string token) { try { SqlParameter[] parameters = { new SqlParameter("@Token", SqlDbType.NVarChar) }; parameters[0].Value = token; _DataHelper = new DataAccessHelper("AdminUser_AuthenticateToken", parameters, _configuration); DataTable dt = new DataTable(); int result = _DataHelper.Run(dt); // 111 /109 DatabaseResponse response = new DatabaseResponse(); AuthTokenResponse tokenResponse = new AuthTokenResponse(); if (result == 111) { if (dt != null && dt.Rows.Count > 0) { tokenResponse = (from model in dt.AsEnumerable() select new AuthTokenResponse() { CustomerID = model.Field <int>("AdminUserID"), CreatedOn = model.Field <DateTime>("CreatedOn") }).FirstOrDefault(); } DatabaseResponse configResponse = ConfigHelper.GetValueByKey(ConfigKeys.CustomerTokenExpiryInDays.ToString(), _configuration); if (configResponse.ResponseCode == (int)DbReturnValue.RecordExists) { if (tokenResponse.CreatedOn < DateTime.Now.AddDays(-int.Parse(configResponse.Results.ToString()))) { tokenResponse.IsExpired = true; } } response = new DatabaseResponse { ResponseCode = result, Results = tokenResponse }; } else { response = new DatabaseResponse { ResponseCode = result }; } return(response); } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw (ex); } finally { _DataHelper.Dispose(); } }
public async Task <DatabaseResponse> LogAdminUserToken(int adminuserId, string token) { try { SqlParameter[] parameters = { new SqlParameter("@AdminUserID", SqlDbType.Int), new SqlParameter("@Token", SqlDbType.NVarChar) }; parameters[0].Value = adminuserId; parameters[1].Value = token; _DataHelper = new DataAccessHelper("AdminUser_CreateToken", parameters, _configuration); DataTable dt = new DataTable(); int result = await _DataHelper.RunAsync(dt); // 100 /105 DatabaseResponse response = new DatabaseResponse(); if (result == 111) { AuthTokenResponse tokenResponse = new AuthTokenResponse(); if (dt != null && dt.Rows.Count > 0) { tokenResponse = (from model in dt.AsEnumerable() select new AuthTokenResponse() { CustomerID = model.Field <int>("AdminUserID"), CreatedOn = model.Field <DateTime>("CreatedOn") }).FirstOrDefault(); } response = new DatabaseResponse { ResponseCode = result, Results = tokenResponse }; } else { response = new DatabaseResponse { ResponseCode = result }; } return(response); } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); throw (ex); } finally { _DataHelper.Dispose(); } }
private string EncryptToken(AuthTokenResponse token, byte[] salt) => Convert.ToBase64String( ProtectedData.Protect( JsonSerializer.SerializeToUtf8Bytes(token), salt, DataProtectionScope.CurrentUser));
public async Task <IActionResult> PostUpdateToken([FromBody] AuthTokenResponse refreshToken) { throw new System.NotImplementedException(); }
public async Task <DatabaseResponse> AuthenticateCustomerToken(string token, string source) { try { SqlParameter[] parameters = { new SqlParameter("@Token", SqlDbType.NVarChar), new SqlParameter("@Source", SqlDbType.NVarChar) }; parameters[0].Value = token; parameters[1].Value = source; _DataHelper = new DataAccessHelper("Customer_AuthenticateTokenwithSource", parameters, _configuration); DataTable dt = new DataTable(); int result = await _DataHelper.RunAsync(dt); // 111 /109 DatabaseResponse response = new DatabaseResponse(); AuthTokenResponse tokenResponse = new AuthTokenResponse(); if (result == 111) { if (dt != null && dt.Rows.Count > 0) { tokenResponse = (from model in dt.AsEnumerable() select new AuthTokenResponse() { CustomerID = model.Field <int>("CustomerID"), CreatedOn = model.Field <DateTime>("CreatedOn") }).FirstOrDefault(); } DatabaseResponse configResponse = ConfigHelper.GetValueByKey(ConfigKeys.CustomerTokenExpiryInDays.ToString(), _configuration); if (configResponse.ResponseCode == (int)DbReturnValue.RecordExists) { if (tokenResponse.CreatedOn < DateTime.Now.AddDays(-int.Parse(configResponse.Results.ToString()))) { tokenResponse.IsExpired = true; } } response = new DatabaseResponse { ResponseCode = result, Results = tokenResponse }; } else { response = new DatabaseResponse { ResponseCode = result }; } return(response); } catch (Exception ex) { throw (ex); } finally { _DataHelper.Dispose(); } }