Exemplo n.º 1
0
Arquivo: api.py Projeto: pnhoang/osqa
def check_password(username,password):
    """connects to external site and submits username/password pair
    return True or False depending on correctness of login
    saves remote unique id and remote session data in table ExternalLoginData
    may raise forms.ValidationError
    """
    host = settings.EXTERNAL_LEGACY_LOGIN_HOST
    port = settings.EXTERNAL_LEGACY_LOGIN_PORT
    ext_site = httplib.HTTPConnection(host,port)

    print 'connected to %s:%s' % (str(host),str(port))

    #custom code. this one does authentication through
    #MediaWiki API
    params = urllib.urlencode({'action':'login','format':'xml',
            'lgname':username,'lgpassword':password})
    headers = {"Content-type": "application/x-www-form-urlencoded",
                'User-Agent':"User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7",
              "Accept": "text/xml"}
    ext_site.request("POST","/wiki/api.php",params,headers)
    response = ext_site.getresponse()
    if response.status != 200:
        raise forms.ValidationError('error ' + response.status + ' ' + response.reason)
    data = response.read().strip()
    ext_site.close()

    print data

    dom = xml.parseString(data)
    login = dom.getElementsByTagName('login')[0]
    result = login.getAttribute('result')
    
    if result == 'Success':
        username = login.getAttribute('lgusername')
        try:
            eld = ExternalLoginData.objects.get(external_username=username)
        except ExternalLoginData.DoesNotExist:
            eld = ExternalLoginData()
        eld.external_username = username
        eld.external_session_data = data
        eld.save()
        return True 
    else:
        error = login.getAttribute('details')
        raise forms.ValidationError(error)
    return False 
Exemplo n.º 2
0
def signup(request):
    #this view works through forum and mediawiki (using apache include virtual injection)
    if request.is_include_virtual and request.REQUEST.get('was_posted','false')=='true':
        POST_INCLUDE_VIRTUAL = True
        POST_DATA = request.GET
    else:
        POST_INCLUDE_VIRTUAL = False
        if request.method == 'POST':
            POST_DATA = request.POST
        else:
            POST_DATA = None

    if POST_DATA:
        form = RegisterForm(POST_DATA)
        if form.is_valid():
            data = form.cleaned_data
            login_name = data['login_name']
            password = data['password']
            first_name = data['first_name']
            last_name = data['last_name']
            screen_name = data['screen_name']
            user_title = data['user_title']
            email = data['email']
            next = data['next']

            #register mediawiki user
            user_real_name = u'%s %s' % (first_name,last_name)
            mwu = MWUser(
                           user_name=login_name,
                           user_first_name = first_name,
                           user_last_name = last_name,
                           user_title = user_title,
                           user_email = email,
                           user_real_name=user_real_name
                        )
            mwu.set_default_options()
            mwu.save()
            #password may need user id so reload it
            mwu = MWUser.objects.get(user_name = login_name)
            mwu.set_password_and_token(password)
            mwu.save()

            #create log message
            mwu_creation_log = Logging(
                                        log_type='newusers',
                                        log_action='create',
                                        log_timestamp=time.strftime(MW_TS),
                                        log_params=str(mwu.user_id),
                                        log_namespace=2,
                                        log_user=mwu,
                                        log_deleted=0,
                                        )
            mwu_creation_log.save()
            mwu_creation_log.show_in_recent_changes(ip=request.META['REMOTE_ADDR'])
            print 'creation log saved'

            #register local user
            User.objects.create_user(screen_name, email, password)
            u = authenticate(username=screen_name, password=password)
            login(request,u)
            u.mediawiki_user = mwu
            u.save()

            #save email feed settings
            subscribe = SimpleEmailSubscribeForm(POST_DATA)
            if subscribe.is_valid():
                subscribe.save(user=u)

            #save external login data
            eld = ExternalLoginData(external_username=login_name, user=u)
            eld.save()

            transaction.commit()#commit so that user becomes visible on the wiki side

            #check password through API and load MW HTTP header session data
            api.check_password(login_name,password)

            print 'wiki login worked'

            #create welcome message on the forum
            u.message_set.create(message=_('Welcome to the OSQA community!'))
            print 'about to send confirmation email'
            send_welcome_email(request, mwu, u)

            if POST_INCLUDE_VIRTUAL:
                questions = Question.objects.exclude(deleted=True, closed=True, answer_accepted=True)
                questions = questions.order_by('-last_activity_at')[:5]
                response = render_to_response('mediawiki/thanks_for_joining.html', \
                                            {
                                                'wiki_user':mwu,
                                                'user':u,
                                                'questions':questions,
                                            },
                                            context_instance = RequestContext(request))
                api.set_login_cookies(response, u)
                #call session middleware now to get the django login cookies
                from django.contrib.sessions.middleware import SessionMiddleware
                sm = SessionMiddleware()
                response = sm.process_response(request,response)
                cookies = response.cookies
                for c in cookies.values():
                    response.write(c.js_output())
            else:
                response = HttpResponseRedirect(next)
                api.set_login_cookies(response, u)

            #set cookies so that user is logged in in the wiki too
            transaction.commit()
            return response
    else:
        form = RegisterForm()

    transaction.commit()
    if request.is_include_virtual:
        template_name = 'mediawiki/mediawiki_signup_content.html'
    else:
        template_name = 'mediawiki/mediawiki_signup.html'
    return render_to_response(template_name,{'form':form},\
                            context_instance=RequestContext(request))