def geolocation(target): try: geo_lookup = GeoLookup( "8b1261f4d109cc1673a33da38adf9d28") # Klucz do api location = geo_lookup.get_location( target) # zebranie informacji dla ip if location is None: return "Nie udało się znaleźć lokalizacji" # jesli nie uda się znaleźć lokalizacji else: geo_info = { "Kod kontynentu": "", "Nazwa kontynentu": "", "Kod kraju": "", "Nazwa kraju": "", "Kod regionu": "", "Nazwa regionu": "", "Miasto": "", "Kod pocztowy": "", "Szerokość geograficzna": "", "Długość geograficzna": "" } del location['location'], location['ip'], location['type'] for key, value in zip(geo_info.keys(), location.values()): geo_info[key] = value return (geo_info) except Exception as e: return e
def GeolocateIP(ip): # geo_data = GeoLookup("<IP Stack API Key Goes Here>") # geo_location = geo_data.get_location(ip) # location_string = "" # location_string += "IP: " location_string += geo_location['ip'] location_string += '\n' location_string += "City: " location_string += geo_location['city'] location_string += '\n' location_string += "State: " location_string += geo_location['region_name'] location_string += '\n' location_string += "Country: " location_string += geo_location['country_name'] location_string += '\n' location_string += "Zip: " location_string += geo_location['zip'] location_string += '\n' location_string += "Latitude: " location_string += str(geo_location['latitude']) location_string += '\n' location_string += "Longitude: " location_string += str(geo_location['longitude']) location_string += '\n' # return location_string
def login(): #User reached route via POST (as by submitting a form via POST) if request.method == "POST": # get client IP address ip = request.form.get('ip') # connect to the API geo_lookup = GeoLookup(os.getenv("API_KEY")) # get the location details location = geo_lookup.get_location(ip) # Get user city city = location['city'] # Get user country country = location['country_name'] # Ensure username was submitted if not request.form.get("username"): return sorry("Please enter your name") # Ensure password was submitted elif not request.form.get("password"): return sorry("Please enter password") # Query database for username rows = db.execute("SELECT * FROM users WHERE name = :username", { "username": request.form.get("username") }).fetchall() # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash( rows[0]["hash"], request.form.get("password")): return sorry("invalide username or/and password") # Remember which user has logged in session["user_id"] = rows[0]["id"] # Update user location with current data db.execute( "UPDATE users SET country = :country, city = :city WHERE id = :user", { "country": country, "city": city, "user": session["user_id"] }) db.commit() # Redirect user to search page return redirect("/search") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html")
def register(request): if request.method == "POST": hobbies = Hobbi.objects.all() username = request.POST["username"] password = request.POST["password"] email = "*****@*****.**" h = request.POST["hobby"] year = int(request.POST["age"]) ip = request.POST["ip"] geo_lookup = GeoLookup(os.getenv("API_KEY")) location = geo_lookup.get_location(ip) country = location["country_name"] city = location["city"] today = datetime.now() age = today.year - year confirm = request.POST["confirm"] if password != confirm: return render(request, "hobbibi/register.html", { "message": "Password does not match", "hobbies": hobbies }) try: user = User.objects.create_user(username, email, password) user.age = age user.city = city user.country = country user.save() ho = Hobbi.objects.get(id=h) hobbi = Hobbies.objects.create(user=user, hobbi=ho) hobbi.save() except IntegrityError: return render(request, "hobbibi/register.html", { "message": "Username already taken", "hobbies": hobbies }) login(request, user) return HttpResponseRedirect(reverse('search')) else: hobbies = Hobbi.objects.all() return render(request, "hobbibi/register.html", {"hobbies": hobbies})
def login_view(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] ip = request.POST["ip"] geo_lookup = GeoLookup(os.getenv("API_KEY")) location = geo_lookup.get_location(ip) country = location["country_name"] city = location["city"] user = authenticate(request, username=username, password=password) if user is not None: user = User.objects.get(username=username) user.country = country user.city = city user.save() login(request, user) return HttpResponseRedirect(reverse("search")) else: return render(request, "hobbibi/login.html", {"message": "Invalid username and/or password."}) else: return render(request, "hobbibi/login.html")
def get_location_data(self, site): if not site: logger.error(f'{site} cannot be empty') raise ValueError site_type = self.payload_validation(site) try: geo_lookup = GeoLookup(settings.IPSTACK_KEY) logger.debug('GeoLookup connection established') except Exception: logger.error('IPStack does not response') raise IPStackError('IPStack does not response') data = geo_lookup.get_location(site_type) if not data['continent_name'] and not data['country_name'] and not data['region_name']: logger.error(f'Site {site_type} does not exist') raise ValueError else: logger.debug(f'Site {site_type} exists') return data
from ipstack import GeoLookup geo_lookup = GeoLookup("acecac3893c90871c3") location = geo_lookup.get_location("github.com") print(location) # Lookup a location for an IP Address # and catch any exceptions that might # be thrown try: # Retrieve the location information for # github.com by using it's hostname. # # This function will work with hostnames # or IP addresses. location = geo_lookup.get_location("github.com") # If we are unable to retrieve the location information # for an IP address, null will be returned. if location is None: print("Failed to find location.") else: # Print the Location dictionary. print(location) except Exception as e: print(e)
def register(): # Show the register page # Query database for list of all hobbies hobbies = db.execute("SELECT * FROM hobbies ORDER BY name ASC").fetchall() # user reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure name was provided if not request.form.get("username"): return sorry("must provide a name") # Ensure password was provided elif not request.form.get("password"): return sorry("must provide a password") # Ensure password was confirmed elif request.form.get("password") != request.form.get("confirm"): return sorry("passwords do not match") # Ensure year of birth was provided elif not request.form.get("year"): return sorry("Please enter your birth year") # Ensure hobby was provided elif not request.form.get("hobby"): return sorry("Please select a hobby") # Ensure App was provided elif not request.form.get("app"): return sorry("Please provide an App") # Ensure link was provided elif not request.form.get("link"): return sorry("Please provide a link to your account in the app") # Query database for same username rows = db.execute("SELECT * FROM users WHERE name = :username", { "username": request.form.get("username") }).fetchall() # Ensure the user does not already exist if len(rows) != 0: return sorry("username already exists") # hash the password before saving it i the database hashed = generate_password_hash(request.form.get("password"), method='pbkdf2:sha256', salt_length=8) # checking the current year currentyear = datetime.utcnow().year # Calculating user age age = int(currentyear) - int(request.form.get("year")) # Getting name from the form name = request.form.get("username") # get client IP address ip = request.form.get('ip') # connect to the API geo_lookup = GeoLookup(os.getenv("API_KEY")) # get the location details location = geo_lookup.get_location(ip) # Get user city city = location['city'] # Get user country country = location['country_name'] # Getting app from the form app = request.form.get("app") # Getting hobby from the form h = request.form.get("hobby") # Getting link from the form link = request.form.get("link") # Adding user information useres table db.execute( "INSERT INTO users (name, hash, age, country, city, app, link) VALUES (:name, :hashed, :age, :country, :city, :app, :link)", { "name": name, "hashed": hashed, "age": age, "country": country, "city": city, "app": app, "link": link }) db.commit() # Query database for assigned user id row = db.execute("SELECT id FROM users WHERE name = :name", { "name": name }).fetchone() # Adding user hobby to hobby table db.execute("INSERT INTO hobby (hobby, user_id) VALUES (:hobby, :user)", { "hobby": h, "user": row[0] }) db.commit() # Remember which user has logged in session["user_id"] = row[0] # Riderict to search page return redirect("/search") # user reached route via GET else: # showing register page and providing lists of countries, cities and hobbies return render_template("register.html", hobbies=hobbies)
with open('list_queries.txt', 'w') as f: print(dic_all_queries, file=f) ###Process the list of users to get the country and city of the IP address ##We used the ipstack. More info: https://ipstack.com/ ##10.000 requests/month key_geolookup = args['key'] geo_lookup = GeoLookup(key_geolookup) ##Process each user to get the country and city and save the result in a list for elem in list_users: IP = elem.split(' &&&& ')[0] if IP not in list_users_processed_country: try: information = geo_lookup.get_location(IP) country = information["country_name"] city = information["city"] list_users_processed_country[IP] = [country, city] except: print( "ERROR Limited Request per Month. Wait to save the IPs processed in a file" ) with open('list_users_processed_country.txt', 'w') as f: print(list_users_processed_country, file=f) ####FIGURES ##################################################################################################################################################################
def orient(ip): #geo_lookup = GeoLookup("431c444c2d03ca049a4356d7d7c897b7") geo_lookup = GeoLookup("f02b34fc34b84c40be72c2299657cef0") location = geo_lookup.get_location(ip) return(location)