public void TestParseEmptyUa() { var dd = new DeviceDetector(); dd.Parse(); dd.Parse(); // call second time complete code coverage }
public void TestParseEmptyUa() { var dd = new DeviceDetector(); dd.Parse(); dd.IsParsed().Should().BeTrue(); dd.Parse(); // call second time complete code coverage dd.IsParsed().Should().BeTrue(); var client = dd.GetClient(); client.Success.Should().BeFalse(); }
/// <summary> /// /// </summary> public Detector(string userAgent) { DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE); DeviceDetector dd = new DeviceDetector(userAgent); // OPTIONAL: Set caching method // By default static cache is used, which works best within one php process (memory array caching) // To cache across requests use caching in files or memcache dd.SetCache(new DictionaryCache()); // OPTIONAL: If called, GetBot() will only return true if a bot was detected (speeds up detection a bit) dd.DiscardBotInformation(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) dd.SkipBotDetection(); dd.Parse(); if (dd.IsBot()) { // handle bots,spiders,crawlers,... var botInfo = dd.GetBot(); } else { var clientInfo = dd.GetClient(); // holds information about browser, feed reader, media player, ... var osInfo = dd.GetOs(); var device = dd.GetDeviceName(); var brand = dd.GetBrandName(); var model = dd.GetModel(); } }
protected override DeviceInformation DoGetDeviceInformation(string userAgent) { Assert.ArgumentNotNull(userAgent, "userAgent"); using (new ReadScope(_readerWriterLockSlim)) { var dd = new DeviceDetector(userAgent); dd.Parse(); var browserMatchResult = dd.GetBrowserClient().Match; DeviceType deviceType = DeviceType.Computer; if (dd.IsMobile()) { deviceType = DeviceType.MobilePhone; } DeviceInformation deviceInformation = new DeviceInformation { Browser = browserMatchResult?.Name ?? "desktop", DeviceIsSmartphone = dd.IsMobile(), DeviceModelName = dd.GetDeviceName(), DeviceType = deviceType, DeviceVendor = dd.GetModel() }; return(deviceInformation); } }
// Generate refresh token private RefreshToken GenerateRefreshToken(string ipAddress, DeviceDetector dd) { dd.Parse(); var refreshToken = new RefreshToken { Token = RandomTokenString(), Expires = DateTime.Now.AddDays(7), Created = DateTime.Now, CreatedByIp = ipAddress, LastActive = DateTime.Now, }; if (!dd.IsBot()) { try { var clientInfo = dd.GetClient().ToString().Replace(" ", "").Split("\n")[1].Split(":")[1].Replace(";", ""); var osInfo = dd.GetOs().ToString().Replace(" ", "").Split("\n")[1].Split(":")[1].Replace(";", ""); var device = dd.GetDeviceName(); var brand = dd.GetBrandName(); var model = dd.GetModel(); refreshToken.Device = model + " " + brand + " " + osInfo + " " + device; refreshToken.Application = clientInfo; } catch { } } return(refreshToken); }
public DeviceInfo BuildFromEventData(string userAgent) { var dd = new DeviceDetector(userAgent); dd.Parse(); var client = (BrowserMatchResult)dd.GetClient().Matches.First(r => r is BrowserMatchResult); var os = dd.GetOs(); if (!BrowserParser.GetBrowserFamily(client.ShortName, out var browserFamily)) { browserFamily = client.ShortName; } if (!OperatingSystemParser.GetOsFamily(os.Match.ShortName, out var osFamily) || osFamily == "GNU/Linux") { osFamily = os.Match.ShortName; } return(new DeviceInfo { Browser = new BrowserInfo() { Name = client.Name + " " + client.Version, Type = browserFamily }, DeviceType = dd.GetDeviceName(), OperatingSystem = new OsInfo() { Name = os.Match.Platform + " " + os.Match.Name + " " + os.Match.Version, Type = osFamily }, UserAgent = userAgent }); }
public IActionResult Index() { var dd = new DeviceDetector(Request.Headers["User-Agent"].ToString()); dd.Parse(); return(View(dd)); }
public void TestIsParsed() { var dd = new DeviceDetector("Mozilla/5.0 (Linux; Android 4.2.2; ARCHOS 101 PLATINUM Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Safari/537.36"); dd.IsParsed().Should().BeFalse(); dd.Parse(); dd.IsParsed().Should().BeTrue(); }
/// <summary> /// Setup and return the device detector /// </summary> /// <param name="userAgent"></param> /// <returns></returns> private static DeviceDetector GetDeviceDetector(string userAgent) { DeviceDetectorSettings.RegexesDirectory = HostingEnvironment.MapPath(@"~\Resources\"); var deviceDetector = new DeviceDetector(userAgent); deviceDetector.SetCache(new DictionaryCache()); deviceDetector.Parse(); return(deviceDetector); }
public void TestParseInvalidUa() { var dd = new DeviceDetector("12345"); dd.Parse(); dd.IsParsed().Should().BeTrue(); var client = dd.GetClient(); client.Success.Should().BeFalse(); }
public async Task <IActionResult> Get() { var userAgent = HttpContext.Request.Headers["User-Agent"].ToString(); if (string.IsNullOrWhiteSpace(userAgent)) { return(BadRequest("User agent could not be determined.")); } var dd = new DeviceDetector(userAgent); dd.Parse(); var device = OrUnknown(dd.GetDeviceName(), "device"); var brand = OrUnknown(dd.GetBrandName(), "brand"); var model = OrUnknown(dd.GetModel(), "model"); var osMatch = dd.GetOs()?.Match; var osName = OrUnknown(osMatch?.Name, "os"); var osPlatform = OrUnknown(osMatch?.Platform, "os-platform"); var osVersion = OrUnknown(osMatch?.Version, "os-version"); var clientMatch = dd.GetClient()?.Match; var clientName = OrUnknown(clientMatch?.Name, "client"); var clientType = OrUnknown(clientMatch?.Type, "client-type"); var clientVersion = OrUnknown(clientMatch?.Version, "client-version"); // var ip = Request.HttpContext.Connection.RemoteIpAddress.ToString(); // This didn't work var ip = HttpContext.Request.Headers["X-Forwarded-For"].ToString(); var city = string.Empty; if (!string.IsNullOrWhiteSpace(ip)) { var apiKey = Environment.GetEnvironmentVariable("IPREGISTRY_KEY"); var url = $"https://api.ipregistry.co/{ip}?key={apiKey}"; var client = _clientFactory.CreateClient(); var reponse = await client.GetAsync(url); var ipReponse = JsonConvert.DeserializeObject <IPResponse>(await reponse.Content.ReadAsStringAsync()); city = ipReponse?.location?.city; } ip = OrUnknown(ip, "ip-address"); city = OrUnknown(city, "city"); return(Ok($"" + $"Device: {device} {brand} {model}\n" + $"OS: {osName} {osPlatform} {osVersion}\n" + $"Client: {clientName} {clientType} {clientVersion}\n" + $"IP: {ip}, near {city}")); }
/// <summary> /// this library get device and user related details to perform first level authentication /// </summary> /// <param name="userAgent"></param> /// <returns>DeviceInfo</returns> public static DeviceInfo Get(string userAgent) { var deviceInfo = new DeviceInfo(); var client = new ClientModel(); var bot = new BotModel(); var os = new OsInfo(); var device = new DeviceDetector(userAgent); device.SetCache(new DictionaryCache()); device.Parse(); if (device.IsBot()) { // checks if the user is a bot or crawler and retrieve the info var botInfo = device.GetBot(); bot.Success = botInfo.Success; bot.Name = botInfo.Matches[0].Name ?? botInfo.Match?.Name; bot.Producer = botInfo.Matches[0].Producer.Name ?? botInfo.Match?.Producer.Name; bot.ProducerUrl = botInfo.Matches[0].Producer.Url ?? botInfo.Match?.Producer.Url; bot.Url = botInfo.Matches[0].Url ?? botInfo.Match?.Url; } else {//if its not a bot get client info var clientInfo = device.GetClient(); client.Name = clientInfo.Matches[0]?.Name ?? clientInfo.Match?.Name; client.Type = clientInfo.Matches[0]?.Type ?? clientInfo.Match?.Type; client.Version = clientInfo.Matches[0]?.Version ?? clientInfo.Match?.Version; client.Success = clientInfo.Success; // holds information about browser, feed reader, media player, ... var osInfo = device.GetOs(); os.Name = osInfo.Matches[0]?.Name ?? osInfo.Match?.Name; os.Version = osInfo.Match?.Version ?? osInfo.Matches[0]?.Version ?? osInfo.Match?.Version; os.PlatForm = osInfo.Match?.Platform ?? osInfo.Matches[0]?.Platform ?? osInfo.Match?.Platform; os.ShortName = osInfo.Match?.ShortName ?? osInfo.Matches[0]?.ShortName ?? osInfo.Match?.ShortName; os.Success = osInfo.Success; client.DeviceName = device.GetDeviceName(); client.DeviceBrandName = device.GetBrandName(); client.DeviceModel = device.GetModel(); } client.IsDesktop = device.IsDesktop(); client.IsMobile = device.IsMobile(); deviceInfo.Bot = bot; deviceInfo.Client = client; deviceInfo.OsInfo = os; return(deviceInfo); }
/// <summary> /// 加入客戶端裝置追蹤擴充 /// </summary> /// <param name="services">DI服務容器</param> /// <returns>DI服務容器</returns> public static void AddDeviceDetector(this IServiceCollection services) { services.AddScoped <DeviceDetector>(sp => { var httpContext = sp.GetService <IHttpContextAccessor>().HttpContext; DeviceDetector detector = null; if (httpContext.Request.Headers.TryGetValue("User-Agent", out StringValues userAgent)) { detector = new DeviceDetector(userAgent); detector.SetCache(new DictionaryCache()); detector.Parse(); } return(detector); }); }
/// <summary> /// LRU cached version of GetDeviceDetector /// </summary> /// <param name="userAgent">used as the key for the cache lookup. /// Note that this does not handle situations where SetVersionTruncation is used because Parse will operate differently based on Version Truncation, which /// is a static variable.</param> /// <returns></returns> public static DeviceDetector GetDeviceDetector(string userAgent) { if (string.IsNullOrEmpty(userAgent)) { return(null); } if (!lruDeviceDetector.TryGetValue(userAgent, out var dd)) { dd = new DeviceDetector(userAgent); dd.SetCache(deviceCache); dd.Parse(); lruDeviceDetector.AddToCache(userAgent, dd); } return(dd); }
public UserAgentDetectorItem getInfo(string userAgent) { DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE); DeviceDetector deviceDetector = new DeviceDetector(userAgent); deviceDetector.Parse(); UserAgentDetectorItem userAgentItem = new UserAgentDetectorItem(); DeviceDetectorResult deviceDetectorResult = ((DeviceDetectorResult)DeviceDetector.GetInfoFromUserAgent(userAgent).Match); ClientMatchResult client = deviceDetector.GetClient().Match; userAgentItem.client_summary = client.Name + " " + client.Version; userAgentItem.ua_family = deviceDetectorResult.BrowserFamily; userAgentItem.ua_version = client.Version; userAgentItem.os_family = deviceDetectorResult.Os.Name; userAgentItem.os_version = deviceDetectorResult.Os.Version; userAgentItem.ua_type = deviceDetector.GetClient().Match.Type; userAgentItem.bot_info = deviceDetector.IsBot(); userAgentItem.os_meta = new Os_meta(); userAgentItem.os_meta.name = deviceDetectorResult.Os.Name; userAgentItem.os_meta.short_name = deviceDetectorResult.Os.ShortName; userAgentItem.os_meta.version = deviceDetectorResult.Os.Version; userAgentItem.os_meta.platform = deviceDetectorResult.Os.Platform; /* String[] info = client.ToString().Split("\n"); * userAgentItem.ua_rendering_engine = info.Length > 4 ? info[4] : ""; * userAgentItem.ua_rendering_engine_version = info.Length > 5 ? info[5] : "";*/ userAgentItem.device = new Device(); userAgentItem.device.is_mobile = deviceDetector.IsMobile(); userAgentItem.device.is_tablet = deviceDetector.IsTablet(); userAgentItem.device.is_desktop = deviceDetector.IsDesktop(); userAgentItem.device.brand = deviceDetectorResult.DeviceBrand; userAgentItem.device.model = deviceDetectorResult.DeviceModel; userAgentItem.client = new Client(); userAgentItem.client.bot = deviceDetector.IsBot(); userAgentItem.client.user = !deviceDetector.IsBot(); return(userAgentItem); }
protected bool IsMobile() { try { var dd = new DeviceDetector(Request.Headers["User-Agent"].ToString()); dd.Parse(); var device = dd.GetDeviceName(); return(device != "desktop"); } catch (Exception e) { Console.WriteLine(e.Message); } return(false); }
/// <summary> /// 解析 User-Agent /// </summary> /// <param name="ua"></param> /// <param name="browserName"></param> /// <param name="systemName"></param> /// <param name="isBot"></param> public static void UserAgentParse(string ua, out string browserName, out string systemName, out bool isBot) { isBot = false; DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE); var bn = "Unknown"; var sn = "Unknown"; if (ua != null) { var dd = new DeviceDetector(ua); dd.Parse(); if (dd.IsBot()) { isBot = true; var botInfo = dd.GetBot(); if (botInfo.Success) { bn = botInfo.Match.Name; } } else { var clientInfo = dd.GetClient(); if (clientInfo.Success) { bn = clientInfo.Match.Name + " " + clientInfo.Match.Version; } var osInfo = dd.GetOs(); if (osInfo.Success) { sn = osInfo.Match.Name + " " + osInfo.Match.Version; } } } browserName = bn; systemName = sn; }
/// <summary> /// 解析 User-Agent /// </summary> /// <param name="ua">User-Agent</param> public UserAgentTo(string ua) { DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE); if (ua != null) { var dd = new DeviceDetector(ua); dd.Parse(); if (dd.IsBot()) { IsBot = true; var botInfo = dd.GetBot(); if (botInfo.Success) { BrowserName = botInfo.Match.Name; } } else { var clientInfo = dd.GetClient(); if (clientInfo.Success) { BrowserName = clientInfo.Match.Name; BrowserType = clientInfo.Match.Type; BrowserVersion = clientInfo.Match.Version; } var osInfo = dd.GetOs(); if (osInfo.Success) { SystemName = osInfo.Match.Name; SystemShortName = osInfo.Match.ShortName; SystemVersion = osInfo.Match.Version; SystemPlatform = osInfo.Match.Platform; } } } }
private DeviceDetector GetDeviceDetectorConfigured() { var ua = _detection.UserAgent; DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE); var dd = new DeviceDetector(ua.ToString()); // OPTIONAL: Set caching method By default static cache is used, which works best within one // php process (memory array caching) To cache across requests use caching in files or // memcache add using DeviceDetectorNET.Cache; dd.SetCache(new DictionaryCache()); // OPTIONAL: If called, GetBot() will only return true if a bot was detected (speeds up // detection a bit) dd.DiscardBotInformation(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as // regular devices then) dd.SkipBotDetection(); dd.Parse(); return(dd); }
public ParsedUA ParseUA() { string ua; if (string.IsNullOrEmpty(UserAgent)) { ua = Request.Headers["User-Agent"].ToString(); } else { ua = UserAgent; } ParsedUA result = new ParsedUA(); var dd = new DeviceDetector(ua); dd.Parse(); if (dd.IsBot()) { result.IsBot = true; result.Bot = dd.GetBot().Match; } else { result.Client = dd.GetClient().Match; result.Os = dd.GetOs().Match; result.Device.DeviceName = dd.GetDeviceName(); result.Device.Model = dd.GetModel(); result.Device.IsDesktop = dd.IsDesktop(); result.Device.IsMobile = dd.IsMobile(); } return(result); }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { if (EXCLUDED_PAGES.Contains(context.Request.Path)) { await next(context); return; } AuthenticatedUserExpanded?user; try { if (context.User?.Identity?.IsAuthenticated != true) { user = _userService.ClaimsPrincipalToAuthenticatedUser(await SignInAnonymousUser(context)); } else { user = _userService.ClaimsPrincipalToAuthenticatedUser(context.User); } if (user is null) { _logger.Warning("Failed to log in neither a proper user nor the anonymous idendity."); await next(context); return; } } catch (Exception ex) { _logger.Warning(ex, "Failed to parse claims"); await next(context); return; } var(isAllowed, dbUser) = await GetDbUserOrAnonymousIfNotAllowed(user); if (!isAllowed) { await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); user = _userService.ClaimsPrincipalToAuthenticatedUser(await SignInAnonymousUser(context)); } var permissionsTask = _userService.GetPermissions(user !.UserId); var tppTask = GetTopicPostsPage(user.UserId); var foesTask = _userService.GetFoes(user.UserId); await Task.WhenAll(permissionsTask, tppTask, foesTask); if (dbUser is null) { var anonymousClaimsPrincipal = await SignInAnonymousUser(context); user = _userService.ClaimsPrincipalToAuthenticatedUser(anonymousClaimsPrincipal); } var sessionTrackingTimeout = _config.GetValue <TimeSpan?>("UserActivityTrackingInterval") ?? TimeSpan.FromHours(1); if (dbUser is not null && !user !.IsAnonymous && ( await _cache.GetAsync <bool?>($"ReloadUser_{user.UsernameClean}") == true || DateTime.UtcNow.Subtract(dbUser.UserLastvisit.ToUtcTime()) > sessionTrackingTimeout)) { var claimsPrincipal = await _userService.DbUserToClaimsPrincipal(dbUser); await Task.WhenAll( SignIn(context, claimsPrincipal), _context.GetDbConnection().ExecuteAsync( "UPDATE phpbb_users SET user_lastvisit = @now WHERE user_id = @userId", new { now = DateTime.UtcNow.ToUnixTimestamp(), user.UserId } ) ); user = _userService.ClaimsPrincipalToAuthenticatedUser(claimsPrincipal); } user !.AllPermissions = await permissionsTask; user.TopicPostsPerPage = await tppTask; user.Foes = await foesTask; context.Items[nameof(AuthenticatedUserExpanded)] = user; if (user.IsAnonymous && context.Request.Headers.TryGetValue(HeaderNames.UserAgent, out var header) && (context.Session.GetInt32("SessionCounted") ?? 0) == 0) { try { var userAgent = header.ToString(); var dd = new DeviceDetector(userAgent); dd.Parse(); var IsBot = dd.IsBot(); if (IsBot) { if (context.Connection.RemoteIpAddress is not null) { _sessionCounter.UpsertBot(context.Connection.RemoteIpAddress.ToString(), userAgent, sessionTrackingTimeout); } } else { context.Session.SetInt32("SessionCounted", 1); _sessionCounter.UpsertSession(context.Session.Id, sessionTrackingTimeout); } } catch (Exception ex) { _logger.Warning(ex, "Failed to detect anonymous session type."); } } await next(context); }
public void TestParseInvalidUa() { var dd = new DeviceDetector("12345"); dd.Parse(); }
[ValidateAntiForgeryToken] //protect against CSRF attacks public async Task <IActionResult> Kontakt(Inquiry inquiry) { var userAgent = Request.Headers["User-Agent"].ToString(); // OPTIONAL: Set version truncation to none, so full versions will be returned // By default only minor versions will be returned (e.g. X.Y) // for other options see VERSION_TRUNCATION_* constants in DeviceParserAbstract class // add using DeviceDetectorNET.Parser; DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE); var dd = new DeviceDetector(userAgent); // OPTIONAL: Set caching method // By default static cache is used, which works best within one php process (memory array caching) // To cache across requests use caching in files or memcache // add using DeviceDetectorNET.Cache; dd.SetCache(new DictionaryCache()); // OPTIONAL: If called, GetBot() will only return true if a bot was detected (speeds up detection a bit) dd.DiscardBotInformation(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) dd.SkipBotDetection(); dd.Parse(); if (dd.IsBot()) { // handle bots,spiders,crawlers,... var botInfo = dd.GetBot(); inquiry.Browser = "BOT"; inquiry.OperatingSystem = "BOT"; inquiry.Device = "BOT"; inquiry.Brand = "BOT"; inquiry.Model = "BOT"; } else { var clientInfo = dd.GetClient(); // holds information about browser, feed reader, media player, ... var osInfo = dd.GetOs(); var device = dd.GetDeviceName(); var brand = dd.GetBrandName(); var model = dd.GetModel(); inquiry.Browser = $"{clientInfo.Match.Name} ({clientInfo.Match.Version})"; inquiry.OperatingSystem = $"{osInfo.Match.Name} ({osInfo.Match.Version}) {osInfo.Match.Platform}"; var deviceResult = device == "" ? inquiry.Device = "N/A" : inquiry.Device = device; var brandResult = brand == "" ? inquiry.Brand = "N/A" : inquiry.Brand = brand; var modelResult = model == "" ? inquiry.Model = "N/A" : inquiry.Model = model; } //local Environment //OperatingSystem os = Environment.OSVersion; //var platform = os.Platform.ToString(); //var version = os.Version.ToString(); //var servicePack = os.ServicePack.ToString(); var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(); inquiry.IpAddress = remoteIpAddress; inquiry.CreatedDate = DateTime.Now; inquiry.Status = "New"; inquiry.HoursSpend = 0; inquiry.HourPrice = 400; inquiry.InvoiceNo = "N/A"; inquiry.Payment = "N/A"; if (ModelState.IsValid) { var inquiryId = await contex.Inquiries.FirstOrDefaultAsync(x => x.Id == inquiry.Id); if (inquiryId != null) { ModelState.AddModelError("", "Nastapil bland, ponow wpis."); return(View()); } //string attachmentName = "noimagecar.png"; //if (inquiry.AttachmentUpload != null) //{ // string uploadsDir = Path.Combine(webHostEnvironment.WebRootPath, "media/cars"); // attachmentName = Guid.NewGuid().ToString() + "_" + inquiry.AttachmentUpload.FileName; // string filePath = Path.Combine(uploadsDir, attachmentName); // FileStream fs = new FileStream(filePath, FileMode.Create); // await inquiry.AttachmentUpload.CopyToAsync(fs); // fs.Close(); //} //inquiry.Attachment = attachmentName; contex.Add(inquiry); await contex.SaveChangesAsync(); TempData["Success"] = "Wiadomosc zostala wyslana!"; return(RedirectToAction("Kontakt")); } return(View()); }