def login_user(request): log = Logger("Login form", "DEBUG") form = None logged = False if request.session.has_key('logged_in'): logged = True if logged or request.method == "POST": form = LoginForm(request.POST) if logged or form.is_valid(): user = username = email = password = None if logged: username = request.session['username'] email = request.session['user_email'] password = request.session['password'] else: username = request.POST['username'] request.session['username'] = username email = request.POST['user_email'] request.session['user_email'] = email password = request.POST['password'] request.session['password'] = password user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) request.session['logged_in'] = True user_id = request.user.id url = "".join([settings.BASE_URL, "/api/rest/all_protocols/?format=json"]) log.message("URL: %s" % (url)) req = urllib2.Request(url, None) opener = urllib2.build_opener() f = opener.open(req) json_response = json.load(f) json_data = json.dumps(json_response) json_dir = os.path.join(settings.PROJECT_ROOT, "json_files") json_file = tempfile.NamedTemporaryFile(mode="w", dir=json_dir, delete=False) user_json_file = UserJSonFile.objects.filter(user_id=user_id, json_type="summary-size") if len(user_json_file) > 0: user_json_file[0].delete() file_path = os.path.join(settings.PROJECT_ROOT, "json_files", user_json_file[0].json_file_name) try: os.unlink(file_path) except: pass file_name = os.path.basename(json_file.name) # save the json data to the temporary file json_file.write(json_data) json_file.close() user_json_file = UserJSonFile(user_id=user_id, json_type="summary-size", json_file_name=file_name) user_json_file.save() context = { 'page_title': 'Welcome to %s' % settings.PROJECT_NAME, 'pcap_operation': "welcome", 'json_file_url': os.path.join(settings.ALTERNATE_BASE_URL, "json_media", file_name), 'json_response': json_response } return render_to_response("main/welcome.html", context, context_instance=RequestContext(request)) else: context = { 'error_message': 'User is not activated!', 'page_title': 'Login Page' } return render_to_response("main/login.html", context, context_instance=RequestContext(request)) else: context = { 'error_message': 'Error occured at the user authentication', 'page_title': 'Login Page' } return render_to_response("main/login.html", context, context_instance=RequestContext(request)) else: context = { 'form': form, 'page_title': 'Login Page' } return render_to_response("main/login.html", context, context_instance=RequestContext(request)) else: form = LoginForm() context = { 'form': form, 'page_title': 'Login Page' } return render_to_response("main/login.html", context, context_instance=RequestContext(request))
def summary(request): # to get this work, runserver should be run as bin/django runserver 127.0.0.0:8001 and another instance should be run as # bin/django runserver log = Logger("Summary:", "DEBUG") context = { 'page_title': 'Summary of the uploaded pcaps', } user_id = request.user.id #session_key = request.session.session_key # TODO: i better keep the user id, login requirements is necessary in this case, for a temporary time use the development USER_ID definition url = "".join([settings.BASE_URL, "/api/rest/protocols/?format=json&user_id=", str(user_id)]) log.message("URL: %s" % (url)) req = urllib2.Request(url, None) opener = urllib2.build_opener() f = None try: f = opener.open(req) json_response = json.load(f) user_id = user_id result = [] response_dict = dict() legend = [] protocols_found = [] for response in json_response: # indeed i have only one response for now, i decided to put all responses in one timeline instead of multiple timelines id = os.urandom(4) response_dict["id"] = "".join([id.encode('hex'), str(user_id)]) response_dict['title'] = "Summary For the Uploaded PCAPs" response_dict['focus_date'] = None # will be fixed response_dict['initial_zoom'] = "38" time_keeper = {'start': None, 'end': None} importance_keeper = [] # events creation starts here events = [] for protocol, values in response.iteritems(): count = 0 for value in values: event_dict = dict() event_dict['id'] = "-".join([response_dict["id"], protocol, str(count)]) event_dict['link'] = reverse('flow_details', args=(value['flow_id'],)) if value.has_key("type") and value['type']: event_dict['title'] = value['type'] else: event_dict['title'] = protocol if value.has_key('description') and value['description']: event_dict['description'] = cgi.escape(value['description']) else: event_dict['description'] = "No description is set" event_dict['startdate'] = value['start'] event_dict['enddate'] = value['end'] dt_start = datetime.datetime.strptime(value['start'], "%Y-%m-%d %H:%M:%S") dt_end = datetime.datetime.strptime(value['end'], "%Y-%m-%d %H:%M:%S") if not time_keeper['start']: time_keeper['start'] = dt_start if dt_start <= time_keeper['start']: time_keeper['start'] = dt_start if not time_keeper['end']: time_keeper['end'] = dt_end if dt_end >= time_keeper['end']: time_keeper['end'] = dt_end event_dict['date_display'] = 'day' ts = int(datetime.datetime.strptime(value['start'], "%Y-%m-%d %H:%M:%S").strftime("%s")) importance = translate_time(ts) #importance = random.randrange(1, 100) event_dict['importance'] = importance event_dict['high_threshold'] = int(importance) + 5 importance_keeper.append(int(importance)) if protocol not in protocols_found: protocols_found.append(protocol) event_dict['icon'] = ICONS[protocol] events.append(event_dict) count += 1 response_dict['events'] = events # calculate the middle of the time mid_point = time_keeper['start'] + ((time_keeper['end'] - time_keeper['start']) / 2) response_dict['focus_date'] = mid_point.isoformat(sep=" ") # calculate initial zoom response_dict['initial_zoom'] = repr(int((importance_keeper[0]+importance_keeper[-1])/2)) for proto in protocols_found: tmp = dict() tmp['title'] = repr(proto) tmp['icon'] = ICONS[proto] legend.append(tmp) response_dict['legend'] = legend result.append(response_dict) json_data = json.dumps(result) json_dir = os.path.join(settings.PROJECT_ROOT, "json_files") json_file = tempfile.NamedTemporaryFile(mode="w", dir=json_dir, delete=False) user_json_file = UserJSonFile.objects.filter(user_id=user_id, json_type="summary") if len(user_json_file) > 0: user_json_file[0].delete() file_path = os.path.join(settings.PROJECT_ROOT, "json_files", user_json_file[0].json_file_name) try: os.unlink(file_path) except: pass file_name = os.path.basename(json_file.name) # save the json data to the temporary file json_file.write(json_data) json_file.close() user_json_file = UserJSonFile(user_id=user_id, json_type="summary", json_file_name=file_name) user_json_file.save() context['json_file_url'] = os.path.join(settings.ALTERNATE_BASE_URL, "json_media", file_name) context['icon_folder'] = os.path.join(settings.ALTERNATE_BASE_URL, "/site_media/jquery_widget/js/timeglider/icons/") context['pcap_operation'] = "summary" context['summary_li'] = ["summary", "file_summary"] # get the summary query infos flow = Flow.objects.filter(user_id=request.user.id) context['flow'] = flow flow_details = FlowDetails.objects.filter(user_id=request.user.id) flow_details_dict = dict() f_d = dict() for flow_detail in flow_details: if not flow_details_dict.has_key(flow_detail.protocol): flow_details_dict[flow_detail.protocol] = dict() f_d = flow_details_dict[flow_detail.protocol] f_d['count'] = 1 f_d['timestamps'] = [flow_detail.timestamp] else: f_d['count'] += 1 f_d['timestamps'].append(flow_detail.timestamp) for key, value in flow_details_dict.items(): ts = flow_details_dict[key]['timestamps'] ts.sort() flow_details_dict[key]['start'] = ts[0] flow_details_dict[key]['end'] = ts[-1] context['flow_details'] = flow_details_dict context['ALTERNATE_BASE_URL'] = settings.ALTERNATE_BASE_URL return render_to_response("pcap/summary.html", context_instance=RequestContext(request, context)) #HttpResponse(json.dumps(response_dict)) except Exception, ex: log.message(ex) raise Http404