Example #1
0
def create_user(request):
    if request.POST:
        form = CreateUserForm(request.POST)

        if form.is_valid():
            user_ = User(username=form.cleaned_data['username'],
                         email=form.cleaned_data['email'])
            user_.set_password(form.cleaned_data['password1'])

            if not form.cleaned_data.get('validate_email', False):
                user_.email_isvalid = True

            user_.save()
            UserJoinsAction(user=user_).save()

            request.user.message_set.create(
                message=_("New user created sucessfully. %s.") %
                html.hyperlink(user_.get_profile_url(),
                               _("See %s profile") % user_.username,
                               target="_blank"))

            return HttpResponseRedirect(
                reverse("admin_tools", kwargs={'name': 'createuser'}))
    else:
        form = CreateUserForm()

    return ('osqaadmin/createuser.html', {
        'form': form,
    })
    def process_authentication_request(self, request):

        # Check for the Shibboleth session header.
        if 'HTTP_SHIB_SESSION_ID' in request.META and request.META['HTTP_SHIB_SESSION_ID']:

            # Fetch the username and email from Shibboleth headers.
            utf8_username = request.META['HTTP_SSONAME'].decode('utf-8')
            # Create an ASCII compatible version of the username,
            # because OSQA/Django have bugs handling UTF8 strings in usernames.
            username = unicodedata.normalize('NFKD', utf8_username).encode('ascii', 'ignore')
            email = request.META['HTTP_SSOCONTACTMAIL']

            # Try to load the user from the database, by its email.
            user = None
            try:
                user = User.objects.get(email=email)
            except:
                pass

            if user is None:
                # The user was not found, so it must be a new user.
                # Let's create it on the database.
                user = User(username=username, email=email)
                user.email_isvalid = True
                user.set_unusable_password()
                user.save()
                UserJoinsAction(user=user, ip=request.META['REMOTE_ADDR']).save()

            # Return the User object of the authenticated user.
            return user

        else:
            raise InvalidAuthentication("Shibboleth Authentication Failure.")
Example #3
0
    def process_authentication_request(self, request):
        username = request.POST["username"].strip()
        password = request.POST["password"]
        uid = str(settings.LDAP_USER_MASK) % username

        # an empty password will cause ldap to try an anonymous bind. This is picked up here
        if not password:
            raise InvalidAuthentication(
                _("Login failed. Please enter valid username and password (both are case-sensitive)")
            )

        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if settings.LDAP_USE_TLS:
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            ldapo.simple_bind_s(str(settings.LDAP_BIND_DN), str(settings.LDAP_BIND_SECRET))
            search = ldapo.search_s(str(settings.LDAP_BASE_DN), ldap.SCOPE_SUBTREE, uid)
        except ldap.LDAPError:
            # could not bind using credentials specified in ldap config
            raise InvalidAuthentication(_("Login failed - LDAP bind error. Please contact your system administrator"))

        ldapo.unbind_s()

        if not search:
            # could not find user
            raise InvalidAuthentication(
                _("Login failed. Please enter valid username and password (both are case-sensitive)")
            )

        # now try to bind as selected user; should raise exception if bind fails
        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if settings.LDAP_USE_TLS:
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            ldapo.simple_bind_s(search[0][1][str(settings.LDAP_DN)][0], password)
        except ldap.LDAPError:
            # could not bind as user - password is incorrect
            raise InvalidAuthentication(
                _("Login failed. Please enter valid username and password (both are case-sensitive)")
            )
        ldapo.unbind_s()

        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            userinfo = search[0][1]
            _user = User(
                username=userinfo[str(settings.LDAP_UID)][0],
                email=userinfo[str(settings.LDAP_MAIL)][0],
                real_name=userinfo[str(settings.LDAP_NAME)][0],
            )
            _user.email_isvalid = True
            _user.set_unusable_password()
            _user.save()
            UserJoinsAction(user=_user, ip=request.META["REMOTE_ADDR"]).save()
            return _user
Example #4
0
    def import_users(self, users):
        pkey_map = {}
        doc = dom.parse(users)

        rows = doc.getElementsByTagName('row')
        unknown_count = 0

        added_names = []

        for row in rows:
            values = self.row_to_dic(row)

            username = values.get('displayname',
                            values.get('realname',
                                values.get('email', None)))

            if username is None:
                unknown_count += 1
                username = '******' % unknown_count

            if username in added_names:
                cnt = 1
                new_username = "******" % (username, cnt)
                while new_username in added_names:
                    cnt += 1
                    new_username = "******" % (username, cnt)

                username = new_username

            added_names.append(username)

            user = User(username=username, email=values.get('email', ''))

            user.reputation = values['reputation']
            user.last_seen = self.from_sx_time(values['lastaccessdate'])

            user.real_name = values.get('realname', '')
            user.about = values.get('aboutme', '')
            user.website = values.get('websiteurl', '')
            user.date_of_birth = self.from_sx_time(values.get('birthday', None))
            user.location = values.get('location', '')

            user.is_active = True
            user.email_isvalid = True


            if int(values['usertypeid']) == 5:
                user.is_superuser = True

            if int(values['usertypeid']) == 5:
                user.is_staff = True

            user.save()

            pkey_map[values['id']] = user

        return users
Example #5
0
File: auth.py Project: sadleb/osqa
def create_user(request):
    if request.method == 'POST' and request.POST['access_token'] == djsettings.BZ_QA_TOKEN:
        assoc_key = request.POST['url']
        username = request.POST['name']
        real_name = request.POST['name']
        email = request.POST['email']
        auth_provider = 'openidurl'

        user_ = User(username=username, email=email, real_name=real_name)
        user_.set_unusable_password()
        user_.email_isvalid = True
        user_.save()
        UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save()

        uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider)
        uassoc.save()
 
        return HttpResponse('OK')
    else:
        raise Http404()
Example #6
0
def update_forum_user(request):
    """ Create or Update Forum User model """

    try:
        # Customise User Model
        # username = request.user.username.split('@')[0]
        user = User.objects.get(user_ptr_id=request.user.id)
        user.user_ptr = request.user
        user.save()
    except ObjectDoesNotExist:
        obj = User()
        obj.user_ptr = request.user
        obj.email_isvalid = True

        obj.last_seen = request.user.last_login
        obj.username = request.user.username if '@' not in request.user.username else request.user.username.split('@')[0]
        obj.real_name = "%s %s" % (request.user.first_name, request.user.last_name)
        # obj.is_active = request.user.is_active
        obj.email = request.user.email
        obj.profile_image_url = request.session['profile_image'] if 'profile_image' in request.session else ''
        obj.save()
Example #7
0
def create_user(request):
    if request.POST:
        form = CreateUserForm(request.POST)

        if form.is_valid():
            user_ = User(username=form.cleaned_data['username'], email=form.cleaned_data['email'])
            user_.set_password(form.cleaned_data['password1'])

            if not form.cleaned_data.get('validate_email', False):
                user_.email_isvalid = True

            user_.save()
            UserJoinsAction(user=user_).save()

            request.user.message_set.create(message=_("New user created sucessfully. %s.") % html.hyperlink(
                    user_.get_profile_url(), _("See %s profile") % user_.username, target="_blank"))

            return HttpResponseRedirect(reverse("admin_tools", kwargs={'name': 'createuser'}))
    else:
        form = CreateUserForm()

    return ('osqaadmin/createuser.html', {
        'form': form,
    })
Example #8
0
def create_user(request):
    if request.POST:
        form = CreateUserForm(request.POST)

        if form.is_valid():
            user_ = User(username=form.cleaned_data["username"], email=form.cleaned_data["email"])
            user_.set_password(form.cleaned_data["password1"])

            if not form.cleaned_data.get("validate_email", False):
                user_.email_isvalid = True

            user_.save()
            UserJoinsAction(user=user_).save()

            request.user.message_set.create(
                message=_("New user created sucessfully. %s.")
                % html.hyperlink(user_.get_profile_url(), _("See %s profile") % user_.username, target="_blank")
            )

            return HttpResponseRedirect(reverse("admin_tools", kwargs={"name": "createuser"}))
    else:
        form = CreateUserForm()

    return ("podporaadmin/createuser.html", {"form": form})
Example #9
0
def external_register(request):
    if request.method == 'POST' and 'bnewaccount' in request.POST:
        form1 = SimpleRegistrationForm(request.POST)

        if form1.is_valid():
            user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'])
            user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email']
            user_.set_unusable_password()

            if User.objects.all().count() == 0:
                user_.is_superuser = True
                user_.is_staff = True

            user_.save()
            UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save()

            try:
                assoc_key = request.session['assoc_key']
                auth_provider = request.session['auth_provider']
            except:
                request.session['auth_error'] = _(
                        "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work."
                        )
                logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
                        ["%s: %s" % (k, v) for k, v in request.META.items()]))
                return HttpResponseRedirect(reverse('auth_signin'))

            uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider)
            uassoc.save()

            del request.session['assoc_key']
            del request.session['auth_provider']

            return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. "))
    else:
        auth_provider = request.session.get('auth_provider', None)
        if not auth_provider:
            request.session['auth_error'] = _(
                    "Oops, something went wrong in the middle of this process. Please try again.")
            logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
                    ["%s: %s" % (k, v) for k, v in request.META.items()]))
            return HttpResponseRedirect(reverse('auth_signin'))

        provider_class = AUTH_PROVIDERS[auth_provider].consumer

        # Hack: Facebook auth expects an access token, not the assoc_key.
        identifier = request.session['assoc_key']
        if auth_provider == 'facebook':
            identifier = request.session['access_token']
        user_data = provider_class.get_user_data(identifier)

        if not user_data:
            user_data = request.session.get('auth_consumer_data', {})

        username = user_data.get('username', '')
        email = user_data.get('email', '')

        if email:
            request.session['auth_validated_email'] = email

        form1 = SimpleRegistrationForm(initial={
        'next': '/',
        'username': username,
        'email': email,
        })

    provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context

    return render_to_response('auth/complete.html', {
    'form1': form1,
    'provider':provider_context and mark_safe(provider_context.human_name) or _('unknown'),
    'login_type':provider_context.id,
    'gravatar_faq_url':reverse('faq') + '#gravatar',
    }, context_instance=RequestContext(request))
Example #10
0
def external_register(request):
    if request.method == 'POST' and 'bnewaccount' in request.POST:
        form1 = SimpleRegistrationForm(request.POST)

        if form1.is_valid():
            user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'])
            user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email']
            user_.set_unusable_password()

            if User.objects.all().count() == 0:
                user_.is_superuser = True
                user_.is_staff = True

            user_.save()
            UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save()

            try:
                assoc_key = request.session['assoc_key']
                auth_provider = request.session['auth_provider']
            except:
                request.session['auth_error'] = _(
                        "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work."
                        )
                logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
                        ["%s: %s" % (k, v) for k, v in request.META.items()]))
                return HttpResponseRedirect(reverse('auth_signin'))

            uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider)
            uassoc.save()

            del request.session['assoc_key']
            del request.session['auth_provider']

            return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. "))
    else:
        auth_provider = request.session.get('auth_provider', None)
        if not auth_provider:
            request.session['auth_error'] = _(
                    "Oops, something went wrong in the middle of this process. Please try again.")
            logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
                    ["%s: %s" % (k, v) for k, v in request.META.items()]))
            return HttpResponseRedirect(reverse('auth_signin'))

        provider_class = AUTH_PROVIDERS[auth_provider].consumer
        user_data = provider_class.get_user_data(request.session['assoc_key'])

        if not user_data:
            user_data = request.session.get('auth_consumer_data', {})

        username = user_data.get('username', '')
        email = user_data.get('email', '')

        if email:
            request.session['auth_validated_email'] = email

        form1 = SimpleRegistrationForm(initial={
        'next': '/',
        'username': username,
        'email': email,
        })

    provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context

    return render_to_response('auth/complete.html', {
    'form1': form1,
    'provider':provider_context and mark_safe(provider_context.human_name) or _('unknown'),
    'login_type':provider_context.id,
    'gravatar_faq_url':reverse('faq') + '#gravatar',
    }, context_instance=RequestContext(request))
    def process_authentication_request(self, request):
        username = request.POST['username'].strip()
        password = request.POST['password']
        uid = str(settings.LDAP_USER_MASK) % username

        #an empty password will cause ldap to try an anonymous bind. This is picked up here
        if not password:
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))

        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if (settings.LDAP_USE_TLS):
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            ldapo.simple_bind_s(str(settings.LDAP_BIND_DN),
                                str(settings.LDAP_BIND_SECRET))
            search = ldapo.search_s(str(settings.LDAP_BASE_DN),
                                    ldap.SCOPE_SUBTREE, uid)
        except ldap.LDAPError:
            #could not bind using credentials specified in ldap config
            raise InvalidAuthentication(
                _('Login failed - LDAP bind error. Please contact your system administrator'
                  ))

        ldapo.unbind_s()

        if not search:
            #could not find user
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))

        #now try to bind as selected user; should raise exception if bind fails
        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if (settings.LDAP_USE_TLS):
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            # F.CRESPEL: use search[0][0] as the DN, so that it works consistently across OpenLDAP/ActiveDirectory
            ###ldapo.simple_bind_s(search[0][1][str(settings.LDAP_DN)][0],password)
            ldapo.simple_bind_s(search[0][0], password)
        except ldap.LDAPError:
            #could not bind as user - password is incorrect
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))
        ldapo.unbind_s()

        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            userinfo = search[0][1]
            _user = User(username=userinfo[str(settings.LDAP_UID)][0],
                         email=userinfo[str(settings.LDAP_MAIL)][0],
                         real_name=userinfo[str(settings.LDAP_NAME)][0])
            _user.email_isvalid = True
            _user.set_unusable_password()
            _user.save()
            UserJoinsAction(user=_user, ip=request.META['REMOTE_ADDR']).save()
            return _user
Example #12
0
def external_register(request):
    if request.method == 'POST' and 'bnewaccount' in request.POST:
        form1 = SimpleRegistrationForm(request.POST)
        email_feeds_form = SimpleEmailSubscribeForm(request.POST)

        if (form1.is_valid() and email_feeds_form.is_valid()):
            user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'])
            user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email']
            user_.set_unusable_password()

            if User.objects.all().count() == 0:
                user_.is_superuser = True
            
            user_.save()

            if not user_.email_isvalid:
                send_validation_email(user_)

            try:
                assoc_key = request.session['assoc_key']
                auth_provider = request.session['auth_provider']
            except:
                request.session['auth_error'] = _("Oops, something went wrong in the middle of this process. Please try again.")
                return HttpResponseRedirect(request.session.get('on_signin_url', reverse('auth_signin'))) 

            uassoc = AuthKeyUserAssociation(user=user_, key=request.session['assoc_key'], provider=request.session['auth_provider'])
            uassoc.save()

            if email_feeds_form.cleaned_data['subscribe'] == 'n':
                user_.subscription_settings.enable_notifications = False
                user_.subscription_settings.save()

            del request.session['assoc_key']
            del request.session['auth_provider']

            if user_.email_isvalid:
                return login_and_forward(request, user_)
            else:
                return HttpResponseRedirect(reverse('index'))
    else:
        provider_class = AUTH_PROVIDERS[request.session['auth_provider']].consumer
        user_data = provider_class.get_user_data(request.session['assoc_key'])

        username = user_data.get('username', '')
        email = user_data.get('email', '')

        if not email:
            email = request.session.get('auth_email_request', '')

        if email:
            request.session['auth_validated_email'] = email

        form1 = SimpleRegistrationForm(initial={
            'next': '/',
            'username': username,
            'email': email,
        })
        email_feeds_form = SimpleEmailSubscribeForm()

    provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context

    return render_to_response('auth/complete.html', {
        'form1': form1,
        'email_feeds_form': email_feeds_form,
        'provider':mark_safe(provider_context.human_name),
        'login_type':provider_context.id,
        'gravatar_faq_url':reverse('faq') + '#gravatar',
    }, context_instance=RequestContext(request))
Example #13
0
def external_register(request):
    if request.method == "POST" and "bnewaccount" in request.POST:
        form1 = SimpleRegistrationForm(request.POST)

        if form1.is_valid():
            user_ = User(
                username=form1.cleaned_data["username"],
                email=form1.cleaned_data["email"],
                real_name=form1.cleaned_data["real_name"],
            )
            user_.email_isvalid = request.session.get("auth_validated_email", "") == form1.cleaned_data["email"]
            user_.set_unusable_password()

            if User.objects.all().count() == 0:
                user_.is_superuser = True
                user_.is_staff = True

            user_.save()
            UserJoinsAction(user=user_, ip=request.META["REMOTE_ADDR"]).save()

            try:
                assoc_key = request.session["assoc_key"]
                auth_provider = request.session["auth_provider"]
            except:
                request.session["auth_error"] = _(
                    "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work."
                )
                logging.error(
                    "Missing session data when trying to complete user registration: %s"
                    % ", ".join(["%s: %s" % (k, v) for k, v in request.META.items()])
                )
                return HttpResponseRedirect(reverse("auth_signin"))

            uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider)
            uassoc.save()

            del request.session["assoc_key"]
            del request.session["auth_provider"]

            return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. "))
    else:
        auth_provider = request.session.get("auth_provider", None)
        if not auth_provider:
            request.session["auth_error"] = _(
                "Oops, something went wrong in the middle of this process. Please try again."
            )
            logging.error(
                "Missing session data when trying to complete user registration: %s"
                % ", ".join(["%s: %s" % (k, v) for k, v in request.META.items()])
            )
            return HttpResponseRedirect(reverse("auth_signin"))

        provider_class = AUTH_PROVIDERS[auth_provider].consumer

        if provider_class.__class__.__name__ == "FacebookAuthConsumer":
            user_data = provider_class.get_user_data(request.session["access_token"])
        else:
            user_data = provider_class.get_user_data(request.session["assoc_key"])

        if not user_data:
            user_data = request.session.get("auth_consumer_data", {})

        username = user_data.get("username", "")
        email = user_data.get("email", "")
        real_name = user_data.get("real_name", "")

        if email:
            request.session["auth_validated_email"] = email

        form1 = SimpleRegistrationForm(
            initial={"next": "/", "username": username, "email": email, "real_name": real_name}
        )

    provider_context = AUTH_PROVIDERS[request.session["auth_provider"]].context

    return render_to_response(
        "auth/complete.html",
        {
            "form1": form1,
            "provider": provider_context and mark_safe(provider_context.human_name) or _("unknown"),
            "login_type": provider_context.id,
            "gravatar_faq_url": reverse("faq") + "#gravatar",
        },
        context_instance=RequestContext(request),
    )
Example #14
0
def external_register(request):
    if request.method == 'POST' and 'bnewaccount' in request.POST:
        form1 = SimpleRegistrationForm(request.POST)        

        if form1.is_valid():
            message= u''
            try:
                user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'], 
                             real_name=form1.cleaned_data.get('real_name', ''))
                user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email']
                user_.set_unusable_password()
    
                if User.objects.all().count() == 0:
                    user_.is_superuser = True
                    user_.is_staff = True
            
                assoc_key = request.session['assoc_key']
                auth_provider = request.session['auth_provider']
                
                user_.save()
                UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save()
                if user_.email_isvalid:
                    EmailValidationAction(user=user_, ip=request.META['REMOTE_ADDR']).save()
                    message += _(u"A welcome email has been sent to Your email address.")
                else:
                    message += _(u"A welcome email has been sent to You.<br />Remember to validate Your email address to be able to fully participate in %s community." % settings.APP_TITLE)
                
                uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider)
                uassoc.save()
                logging.info(u"User %s joined via %s" % (user_.username, auth_provider))
            except:
                request.session['auth_error'] = _(
                        "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work."
                        )
                logging.exception("Missing session data when trying to complete user registration: %s" % ", ".join(
                        ["%s: %s" % (k, v) for k, v in request.META.items()]))
                return HttpResponseRedirect(reverse('auth_signin'))           

            _cleanup_after_external_signin(request)
            return login_and_forward(request, user_, message=message)
        else:
            logging.info("Form not validated in external_register %s", str(form1.errors))
    else:        
        auth_provider = request.session.get('auth_provider', None)
        if not auth_provider:
            request.session['auth_error'] = _(
                    "Oops, something went wrong in the middle of this process. Please try again.")
            logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
                    ["%s: %s" % (k, v) for k, v in request.META.items()]))
            return HttpResponseRedirect(reverse('auth_signin'))

        provider_class = AUTH_PROVIDERS[auth_provider].consumer

        if provider_class.__class__.__name__ == 'FacebookAuthConsumer' or provider_class.__class__.__name__ == 'GoogleAuthConsumer':
            user_data = provider_class.get_user_data(request.session['access_token'])
        else:
            user_data = provider_class.get_user_data(request.session['assoc_key'])


        if not user_data:
            user_data = request.session.get('auth_consumer_data', {})

        username = user_data.get('username', '')
        email = user_data.get('email', '')
        real_name = user_data.get('real_name', '')

        if email:
            try:
                old_user = User.objects.get(email=email)
                message=_("Welcome back %s! You can now login via %s.") % (old_user.username, auth_provider.capitalize())
                if not old_user.email_isvalid:
                    message += _("<br />Since this email was not previously validated we cleared your password.<br />Set new one to be able to login with it")
                    old_user.set_unusable_password()
                    old_user.email_isvalid = True
                    old_user.save()
                    logging.warning("Clearing password for user %s with unvalidated email after signing with %s" % 
                                    (old_user.username, auth_provider))
                    EmailValidationAction(user=old_user, ip=request.META['REMOTE_ADDR']).save()
                uassoc = AuthKeyUserAssociation(user=old_user, key=request.session['assoc_key'], provider=auth_provider)
                uassoc.save()
                logging.info(u"User %s added %s sign in provider" % (old_user.username, auth_provider))
                _cleanup_after_external_signin(request)
                return login_and_forward(request, old_user, message=mark_safe(message))
            except:
                pass
            request.session['auth_validated_email'] = email

        form1 = SimpleRegistrationForm(initial={
        'next': '/',
        'username': username,
        'email': email,
        'real_name': real_name,
        })

    provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context

    return render_to_response('auth/complete.html', {
    'form1': form1,
    'provider':provider_context and mark_safe(provider_context.human_name) or _('unknown'),
    'login_type':provider_context.id,
    'gravatar_faq_url':reverse('faq') + '#gravatar',
    }, context_instance=RequestContext(request))
Example #15
0
def external_register(request):
    if request.method == 'POST' and 'bnewaccount' in request.POST:
        form1 = SimpleRegistrationForm(request.POST)
        email_feeds_form = SimpleEmailSubscribeForm(request.POST)

        if (form1.is_valid() and email_feeds_form.is_valid()):
            user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'])
            user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email']
            user_.set_unusable_password()

            if User.objects.all().count() == 0:
                user_.is_superuser = True
            
            user_.save()

            if not user_.email_isvalid:
                send_validation_email(user_)

            try:
                assoc_key = request.session['assoc_key']
                auth_provider = request.session['auth_provider']
            except:
                request.session['auth_error'] = _("Oops, something went wrong in the middle of this process. Please try again.")
                return HttpResponseRedirect(request.session.get('on_signin_url', reverse('auth_signin'))) 

            uassoc = AuthKeyUserAssociation(user=user_, key=request.session['assoc_key'], provider=request.session['auth_provider'])
            uassoc.save()

            if email_feeds_form.cleaned_data['subscribe'] == 'n':
                user_.subscription_settings.enable_notifications = False
                user_.subscription_settings.save()

            del request.session['assoc_key']
            del request.session['auth_provider']

            if user_.email_isvalid:
                return login_and_forward(request, user_)
            else:
                return HttpResponseRedirect(reverse('index'))
    else:
        provider_class = AUTH_PROVIDERS[request.session['auth_provider']].consumer
        user_data = provider_class.get_user_data(request.session['assoc_key'])

        username = user_data.get('username', '')
        email = user_data.get('email', '')

        if not email:
            email = request.session.get('auth_email_request', '')

        if email:
            request.session['auth_validated_email'] = email

        form1 = SimpleRegistrationForm(initial={
            'next': '/',
            'username': username,
            'email': email,
        })
        email_feeds_form = SimpleEmailSubscribeForm()

    provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context

    return render_to_response('auth/complete.html', {
        'form1': form1,
        'email_feeds_form': email_feeds_form,
        'provider':mark_safe(provider_context.human_name),
        'login_type':provider_context.id,
        'gravatar_faq_url':reverse('faq') + '#gravatar',
    }, context_instance=RequestContext(request))
Example #16
0
def external_register(request):
    if request.method == 'POST' and 'bnewaccount' in request.POST:
        form1 = SimpleRegistrationForm(request.POST)

        if form1.is_valid():
            user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'])
            user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email']
            user_.set_unusable_password()

            if User.objects.all().count() == 0:
                user_.is_superuser = True
                user_.is_staff = True

            user_.save()

            try:
                assoc_key = request.session['assoc_key']
                auth_provider = request.session['auth_provider']
                if auth_provider == "weibo":
                    token = ast.literal_eval(assoc_key)
                    assoc_key = token["access_token"]
                    weibo_uid = token["uid"]
                    weibo_remind_in = token["remind_in"]
                    weibo_expires_at = token["expires_at"]

            except:
                request.session['auth_error'] = _(
                        "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work."
                        )
                logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
                        ["%s: %s" % (k, v) for k, v in request.META.items()]))
                return HttpResponseRedirect(reverse('auth_signin'))

            if auth_provider == "weibo":
                uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider,weibo_uid=weibo_uid,weibo_remind_in=weibo_remind_in,weibo_expires_at=weibo_expires_at)
            else:
                uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider)
            uassoc.save()

            UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save()
            del request.session['assoc_key']
            del request.session['auth_provider']

            return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. "))
    else:
        auth_provider = request.session.get('auth_provider', None)
        if not auth_provider:
            request.session['auth_error'] = _(
                    "Oops, something went wrong in the middle of this process. Please try again.")
            logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
                    ["%s: %s" % (k, v) for k, v in request.META.items()]))
            return HttpResponseRedirect(reverse('auth_signin'))

        if auth_provider == 'weibo':
            assoc_key = request.session['assoc_key']
            token = ast.literal_eval(assoc_key)
            client = weibo_client(str(settings.WEIBO_API_KEY), str(settings.WEIBO_API_SECRET),urlparse.urljoin(settings.APP_URL,'/weibo/signin/check'),token)
            user=client.get('users/show', uid=token["uid"])
            username = user["name"]
            email = None
            provider_context = None

        else: # weibo user register
            provider_class = AUTH_PROVIDERS[auth_provider].consumer
            user_data = provider_class.get_user_data(request.session['assoc_key'])

            if not user_data:
                user_data = request.session.get('auth_consumer_data', {})

            username = user_data.get('username', '')
            email = user_data.get('email', '')

            provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context

        if email:
            request.session['auth_validated_email'] = email

        form1 = SimpleRegistrationForm(initial={
        'next': '/',
        'username': username,
        'email': email,
        })


    return render_to_response('auth/complete.html', {
    'form1': form1,
    #'provider':provider_context and mark_safe(provider_context.human_name) or _('unknown'),
    #'login_type':provider_context.id,
    'gravatar_faq_url':reverse('faq') + '#gravatar',
    }, context_instance=RequestContext(request))