当前位置: 首页>>代码示例>>Python>>正文


Python ExternalAuthMap.user方法代码示例

本文整理汇总了Python中openedx.core.djangoapps.external_auth.models.ExternalAuthMap.user方法的典型用法代码示例。如果您正苦于以下问题:Python ExternalAuthMap.user方法的具体用法?Python ExternalAuthMap.user怎么用?Python ExternalAuthMap.user使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在openedx.core.djangoapps.external_auth.models.ExternalAuthMap的用法示例。


在下文中一共展示了ExternalAuthMap.user方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _external_login_or_signup

# 需要导入模块: from openedx.core.djangoapps.external_auth.models import ExternalAuthMap [as 别名]
# 或者: from openedx.core.djangoapps.external_auth.models.ExternalAuthMap import user [as 别名]
def _external_login_or_signup(request,
                              external_id,
                              external_domain,
                              credentials,
                              email,
                              fullname,
                              retfun=None):
    """Generic external auth login or signup"""
    # pylint: disable=too-many-statements
    # see if we have a map from this external_id to an edX username
    try:
        eamap = ExternalAuthMap.objects.get(external_id=external_id,
                                            external_domain=external_domain)
        log.debug(u'Found eamap=%s', eamap)
    except ExternalAuthMap.DoesNotExist:
        # go render form for creating edX user
        eamap = ExternalAuthMap(external_id=external_id,
                                external_domain=external_domain,
                                external_credentials=json.dumps(credentials))
        eamap.external_email = email
        eamap.external_name = fullname
        eamap.internal_password = generate_password()
        log.debug(u'Created eamap=%s', eamap)
        eamap.save()

    log.info(u"External_Auth login_or_signup for %s : %s : %s : %s", external_domain, external_id, email, fullname)
    uses_shibboleth = settings.FEATURES.get('AUTH_USE_SHIB') and external_domain.startswith(SHIBBOLETH_DOMAIN_PREFIX)
    uses_certs = settings.FEATURES.get('AUTH_USE_CERTIFICATES')
    internal_user = eamap.user
    if internal_user is None:
        if uses_shibboleth:
            # If we are using shib, try to link accounts
            # For Stanford shib, the email the idp returns is actually under the control of the user.
            # Since the id the idps return is not user-editable, and is of the from "[email protected]",
            # use the id to link accounts instead.
            try:
                link_user = User.objects.get(email=eamap.external_id)
                if not ExternalAuthMap.objects.filter(user=link_user).exists():
                    # if there's no pre-existing linked eamap, we link the user
                    eamap.user = link_user
                    eamap.save()
                    internal_user = link_user
                    log.info(u'SHIB: Linking existing account for %s', eamap.external_id)
                    # now pass through to log in
                else:
                    # otherwise, there must have been an error, b/c we've already linked a user with these external
                    # creds
                    failure_msg = _(
                        "You have already created an account using "
                        "an external login like WebAuth or Shibboleth. "
                        "Please contact {tech_support_email} for support."
                    ).format(
                        tech_support_email=get_value('email_from_address', settings.TECH_SUPPORT_EMAIL),
                    )
                    return default_render_failure(request, failure_msg)
            except User.DoesNotExist:
                log.info(u'SHIB: No user for %s yet, doing signup', eamap.external_email)
                return _signup(request, eamap, retfun)
        else:
            log.info(u'No user for %s yet. doing signup', eamap.external_email)
            return _signup(request, eamap, retfun)

    # We trust shib's authentication, so no need to authenticate using the password again
    uname = internal_user.username
    if uses_shibboleth:
        user = internal_user
        # Assuming this 'AUTHENTICATION_BACKENDS' is set in settings, which I think is safe
        if settings.AUTHENTICATION_BACKENDS:
            auth_backend = settings.AUTHENTICATION_BACKENDS[0]
        else:
            auth_backend = 'ratelimitbackend.backends.RateLimitModelBackend'
        user.backend = auth_backend
        if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
            AUDIT_LOG.info(u'Linked user.id: {0} logged in via Shibboleth'.format(user.id))
        else:
            AUDIT_LOG.info(u'Linked user "{0}" logged in via Shibboleth'.format(user.email))
    elif uses_certs:
        # Certificates are trusted, so just link the user and log the action
        user = internal_user
        user.backend = 'ratelimitbackend.backends.RateLimitModelBackend'
        if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
            AUDIT_LOG.info(u'Linked user_id {0} logged in via SSL certificate'.format(user.id))
        else:
            AUDIT_LOG.info(u'Linked user "{0}" logged in via SSL certificate'.format(user.email))
    else:
        user = authenticate(username=uname, password=eamap.internal_password, request=request)
    if user is None:
        # we want to log the failure, but don't want to log the password attempted:
        if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
            AUDIT_LOG.warning(u'External Auth Login failed')
        else:
            AUDIT_LOG.warning(u'External Auth Login failed for "{0}"'.format(uname))
        return _signup(request, eamap, retfun)

    if not user.is_active:
        if settings.FEATURES.get('BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH'):
            # if BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH, we trust external auth and activate any users
            # that aren't already active
            user.is_active = True
            user.save()
#.........这里部分代码省略.........
开发者ID:Lektorium-LLC,项目名称:edx-platform,代码行数:103,代码来源:views.py

示例2: create_user

# 需要导入模块: from openedx.core.djangoapps.external_auth.models import ExternalAuthMap [as 别名]
# 或者: from openedx.core.djangoapps.external_auth.models.ExternalAuthMap import user [as 别名]
    def create_user(self, uname, name, password=None):
        """ Creates a user (both SSL and regular)"""

        if not uname:
            return _('Must provide username')
        if not name:
            return _('Must provide full name')

        email_domain = getattr(settings, 'SSL_AUTH_EMAIL_DOMAIN', 'MIT.EDU')

        msg = u''
        if settings.FEATURES['AUTH_USE_CERTIFICATES']:
            if '@' not in uname:
                email = '{0}@{1}'.format(uname, email_domain)
            else:
                email = uname
            if not email.endswith('@{0}'.format(email_domain)):
                # Translators: Domain is an email domain, such as "@gmail.com"
                msg += _('Email address must end in {domain}').format(domain="@{0}".format(email_domain))
                return msg
            mit_domain = 'ssl:MIT'
            if ExternalAuthMap.objects.filter(external_id=email,
                                              external_domain=mit_domain):
                msg += _('Failed - email {email_addr} already exists as {external_id}').format(
                    email_addr=email,
                    external_id="external_id"
                )
                return msg
            new_password = generate_password()
        else:
            if not password:
                return _('Password must be supplied if not using certificates')

            email = uname

            if '@' not in email:
                msg += _('email address required (not username)')
                return msg
            new_password = password

        user = User(username=uname, email=email, is_active=True)
        user.set_password(new_password)
        try:
            user.save()
        except IntegrityError:
            msg += _('Oops, failed to create user {user}, {error}').format(
                user=user,
                error="IntegrityError"
            )
            return msg

        reg = Registration()
        reg.register(user)

        profile = UserProfile(user=user)
        profile.name = name
        profile.save()

        if settings.FEATURES['AUTH_USE_CERTIFICATES']:
            credential_string = getattr(settings, 'SSL_AUTH_DN_FORMAT_STRING',
                                        '/C=US/ST=Massachusetts/O=Massachusetts Institute of Technology/OU=Client CA v1/CN={0}/emailAddress={1}')
            credentials = credential_string.format(name, email)
            eamap = ExternalAuthMap(
                external_id=email,
                external_email=email,
                external_domain=mit_domain,
                external_name=name,
                internal_password=new_password,
                external_credentials=json.dumps(credentials),
            )
            eamap.user = user
            eamap.dtsignup = timezone.now()
            eamap.save()

        msg += _('User {user} created successfully!').format(user=user)
        return msg
开发者ID:AlexxNica,项目名称:edx-platform,代码行数:78,代码来源:sysadmin.py

示例3: handle

# 需要导入模块: from openedx.core.djangoapps.external_auth.models import ExternalAuthMap [as 别名]
# 或者: from openedx.core.djangoapps.external_auth.models.ExternalAuthMap import user [as 别名]
    def handle(self, *args, **options):

        while True:
            uname = raw_input('username: ')
            if User.objects.filter(username=uname):
                print "username %s already taken" % uname
            else:
                break

        make_eamap = False
        if raw_input('Create MIT ExternalAuth? [n] ').lower() == 'y':
            email = '%[email protected]' % uname
            if not email.endswith('@MIT.EDU'):
                print "Failed - email must be @MIT.EDU"
                sys.exit(-1)
            mit_domain = 'ssl:MIT'
            if ExternalAuthMap.objects.filter(external_id=email, external_domain=mit_domain):
                print "Failed - email %s already exists as external_id" % email
                sys.exit(-1)
            make_eamap = True
            password = GenPasswd(12)

            # get name from kerberos
            try:
                kname = os.popen("finger %s | grep 'name:'" % email).read().strip().split('name: ')[1].strip()
            except:
                kname = ''
            name = raw_input('Full name: [%s] ' % kname).strip()
            if name == '':
                name = kname
            print "name = %s" % name
        else:
            while True:
                password = getpass()
                password2 = getpass()
                if password == password2:
                    break
                print "Oops, passwords do not match, please retry"

            while True:
                email = raw_input('email: ')
                if User.objects.filter(email=email):
                    print "email %s already taken" % email
                else:
                    break

            name = raw_input('Full name: ')

        user = User(username=uname, email=email, is_active=True)
        user.set_password(password)
        try:
            user.save()
        except IntegrityError:
            print "Oops, failed to create user %s, IntegrityError" % user
            raise

        r = Registration()
        r.register(user)

        up = UserProfile(user=user)
        up.name = name
        up.save()

        if make_eamap:
            credentials = "/C=US/ST=Massachusetts/O=Massachusetts Institute of Technology/OU=Client CA v1/CN=%s/emailAddress=%s" % (name, email)
            eamap = ExternalAuthMap(
                external_id=email,
                external_email=email,
                external_domain=mit_domain,
                external_name=name,
                internal_password=password,
                external_credentials=json.dumps(credentials),
            )
            eamap.user = user
            eamap.dtsignup = datetime.datetime.now(UTC)
            eamap.save()

        print "User %s created successfully!" % user

        if not raw_input('Add user %s to any groups? [n] ' % user).lower() == 'y':
            sys.exit(0)

        print "Here are the groups available:"

        groups = [str(g.name) for g in Group.objects.all()]
        print groups

        completer = MyCompleter(groups)
        readline.set_completer(completer.complete)
        readline.parse_and_bind('tab: complete')

        while True:
            gname = raw_input("Add group (tab to autocomplete, empty line to end): ")
            if not gname:
                break
            if gname not in groups:
                print "Unknown group %s" % gname
                continue
            g = Group.objects.get(name=gname)
            user.groups.add(g)
#.........这里部分代码省略.........
开发者ID:Lektorium-LLC,项目名称:edx-platform,代码行数:103,代码来源:create_user.py


注:本文中的openedx.core.djangoapps.external_auth.models.ExternalAuthMap.user方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。