Exemple #1
0
    def setUp(self):
        super(OrganizationsApiTests, self).setUp()
        self.test_server_prefix = 'https://testserver'
        self.base_organizations_uri = '/api/server/organizations/'
        self.base_users_uri = '/api/server/users'
        self.base_groups_uri = '/api/server/groups'
        self.test_organization_name = str(uuid.uuid4())
        self.test_organization_display_name = 'Test Org'
        self.test_organization_contact_name = 'John Org'
        self.test_organization_contact_email = '*****@*****.**'
        self.test_organization_contact_phone = '+1 332 232 24234'
        self.test_organization_logo_url = 'org_logo.jpg'

        self.test_user_email = str(uuid.uuid4())
        self.test_user_username = str(uuid.uuid4())
        self.test_user = User.objects.create(email=self.test_user_email,
                                             username=self.test_user_username)
        profile = UserProfile(user=self.test_user)
        profile.city = 'Boston'
        profile.save()

        self.test_user2 = User.objects.create(email=str(uuid.uuid4()),
                                              username=str(uuid.uuid4()))
        profile2 = UserProfile(user=self.test_user2)
        profile2.city = 'NYC'
        profile2.save()

        self.course = CourseFactory.create()
        self.second_course = CourseFactory.create(number="899")

        cache.clear()
Exemple #2
0
def create_new_user(name=''):
    """
    new user
    :return:
    """
    def create_():
        password = TIANYUYUN_PASSWORD
        username = gen_union_username()
        email = '*****@*****.**' % username
        user = User(username=username, email=email, is_active=True)
        user.set_password(password)
        try:
            user.save()
        except:
            return None
        return user

    user = create_()
    if not user:
        while True:
            user = create_()
            if user:
                break
    # TODO UserProfile
    try:
        from student.models import UserProfile
        profile_name = name or 'someone'
        profile = UserProfile(user=user, name='someone')
        profile.save()
    except:
        pass

    return user
Exemple #3
0
def create_lti_user(lti_user_id, lti_consumer):
    """
    Generate a new user on the edX platform with a random username and password,
    and associates that account with the LTI identity.
    """
    edx_password = str(uuid.uuid4())

    created = False
    while not created:
        try:
            edx_user_id = generate_random_edx_username()
            edx_email = "{}@{}".format(edx_user_id, settings.LTI_USER_EMAIL_DOMAIN)
            edx_user = User.objects.create_user(
                username=edx_user_id,
                password=edx_password,
                email=edx_email,
            )
            # A profile is required if PREVENT_CONCURRENT_LOGINS flag is set.
            # TODO: We could populate user information from the LTI launch here,
            # but it's not necessary for our current uses.
            edx_user_profile = UserProfile(user=edx_user)
            edx_user_profile.save()
            created = True
        except IntegrityError:
            # The random edx_user_id wasn't unique. Since 'created' is still
            # False, we will retry with a different random ID.
            pass

    lti_user = LtiUser(
        lti_consumer=lti_consumer,
        lti_user_id=lti_user_id,
        edx_user=edx_user
    )
    lti_user.save()
    return lti_user
Exemple #4
0
    def make_student(self, block, name, **state):
        answer = {}
        for key in ("sha1", "mimetype", "filename"):
            if key in state:
                answer[key] = state.pop(key)
        score = state.pop("score", None)

        user = User(username=name)
        user.save()
        profile = UserProfile(user=user, name=name)
        profile.save()
        module = StudentModule(
            module_state_key=block.location, student=user, course_id=self.course_id, state=json.dumps(state)
        )
        module.save()

        anonymous_id = anonymous_id_for_user(user, self.course_id)
        item = StudentItem(student_id=anonymous_id, course_id=self.course_id, item_id=block.block_id, item_type="sga")
        item.save()

        if answer:
            student_id = block.student_submission_id(anonymous_id)
            submission = submissions_api.create_submission(student_id, answer)
            if score is not None:
                submissions_api.set_score(submission["uuid"], score, block.max_score())
        else:
            submission = None

        self.addCleanup(item.delete)
        self.addCleanup(profile.delete)
        self.addCleanup(module.delete)
        self.addCleanup(user.delete)

        return {"module": module, "item": item, "submission": submission}
Exemple #5
0
    def setUp(self):
        self.test_server_prefix = 'https://testserver'
        self.base_organizations_uri = '/api/server/organizations/'
        self.base_users_uri = '/api/server/users'
        self.base_groups_uri = '/api/server/groups'
        self.test_organization_name = str(uuid.uuid4())
        self.test_organization_display_name = 'Test Org'
        self.test_organization_contact_name = 'John Org'
        self.test_organization_contact_email = '*****@*****.**'
        self.test_organization_contact_phone = '+1 332 232 24234'

        self.test_user_email = str(uuid.uuid4())
        self.test_user_username = str(uuid.uuid4())
        self.test_user = User.objects.create(
            email=self.test_user_email,
            username=self.test_user_username
        )
        profile = UserProfile(user=self.test_user)
        profile.city = 'Boston'
        profile.save()

        self.course = CourseFactory.create()
        self.second_course = CourseFactory.create(
            number="899"
        )

        self.client = SecureClient()
        cache.clear()
Exemple #6
0
def create_lti_user(lti_user_id, lti_consumer):
    """
    Generate a new user on the edX platform with a random username and password,
    and associates that account with the LTI identity.
    """
    edx_password = str(uuid.uuid4())

    created = False
    while not created:
        try:
            edx_user_id = generate_random_edx_username()
            edx_email = "{}@{}".format(edx_user_id,
                                       settings.LTI_USER_EMAIL_DOMAIN)
            edx_user = User.objects.create_user(
                username=edx_user_id,
                password=edx_password,
                email=edx_email,
            )
            # A profile is required if PREVENT_CONCURRENT_LOGINS flag is set.
            # TODO: We could populate user information from the LTI launch here,
            # but it's not necessary for our current uses.
            edx_user_profile = UserProfile(user=edx_user)
            edx_user_profile.save()
            created = True
        except IntegrityError:
            # The random edx_user_id wasn't unique. Since 'created' is still
            # False, we will retry with a different random ID.
            pass

    lti_user = LtiUser(lti_consumer=lti_consumer,
                       lti_user_id=lti_user_id,
                       edx_user=edx_user)
    lti_user.save()
    return lti_user
def import_user_submit(request):
    message={}
    if request.method == 'POST':
        f=request.FILES['file']
        try:
            count_success=0
            # --- THIS FAILS ON SING COLUMN CVS ---
            # dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,")
            # f.seek(0)
            # r=csv.reader(f,dialect)
            r=csv.reader(f,delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            rl = []
            rl.extend(r)
            cohort_id=request.POST.get("cohort_id")
            cohort=Cohort.objects.get(id=cohort_id)
            if cohort.licences < UserProfile.objects.filter(~Q(subscription_status = "Inactive"),cohort_id=cohort_id).count() + len(rl):
                raise Exception("Licences limit exceeded")
            for line in rl:
                exist=validate_user_cvs_line(line)
                # if(exist):
                #     raise Exception("An user already exists, or duplicate lines.")
                email=line[USER_CSV_COL_EMAIL]
                import random
                username=random_mark(20)
                user = User(username=username, email=email, is_active=False)
                user.set_password(username)
                user.save()
                registration = Registration()
                registration.register(user)
                profile=UserProfile(user=user)
                # profile.transaction_id=transaction_id
                # profile.email=email
                # profile.username=username
                profile.cohort_id=cohort_id
                profile.subscription_status="Imported"
                profile.save()

                cea, _ = CourseEnrollmentAllowed.objects.get_or_create(course_id='PCG_Education/PEP101.1/S2016', email=email)
                cea.is_active = True
                cea.auto_enroll = True
                cea.save()

                count_success=count_success+1

                # reg = Registration.objects.get(user=user)
                # d = {'name': profile.name, 'key': reg.activation_key}
                # subject = render_to_string('emails/activation_email_subject.txt', d)
                # subject = ''.join(subject.splitlines())
                # message = render_to_string('emails/activation_emailh.txt', d)
            db.transaction.commit()
            message={"success": True,
                "message":"Success! %s users imported." % (count_success),
                "count_success":count_success,
            }
        except Exception as e:
            db.transaction.rollback()
            message={'success': False,'error':'Import error: %s. At cvs line: %s, Nobody imported.' % (e,count_success+1)}
    return HttpResponse(json.dumps(message))
    def make_student(self, block, name, make_state=True, **state):
        """
        Create a student along with submission state.
        """
        answer = {}
        module = None
        for key in ('sha1', 'mimetype', 'filename', 'finalized'):
            if key in state:
                answer[key] = state.pop(key)
        score = state.pop('score', None)

        with transaction.atomic():
            user = User(username=name)
            user.save()
            profile = UserProfile(user=user, name=name)
            profile.save()
            if make_state:
                module = StudentModule(
                    module_state_key=block.location,
                    student=user,
                    course_id=self.course_id,
                    state=json.dumps(state))
                module.save()

            anonymous_id = anonymous_id_for_user(user, self.course_id)
            item = StudentItem(
                student_id=anonymous_id,
                course_id=self.course_id,
                item_id=block.block_id,
                item_type='sga')
            item.save()

            if answer:
                student_id = block.get_student_item_dict(anonymous_id)
                submission = submissions_api.create_submission(student_id, answer)
                if score is not None:
                    submissions_api.set_score(
                        submission['uuid'], score, block.max_score())
            else:
                submission = None

            self.addCleanup(item.delete)
            self.addCleanup(profile.delete)
            self.addCleanup(user.delete)

            if make_state:
                self.addCleanup(module.delete)
                return {
                    'module': module,
                    'item': item,
                    'submission': submission
                }

            return {
                'item': item,
                'submission': submission
            }
    def make_student(self, block, name, make_state=True, **state):
        """
        Create a student along with submission state.
        """
        answer = {}
        module = None
        for key in ('sha1', 'mimetype', 'filename', 'finalized'):
            if key in state:
                answer[key] = state.pop(key)
        score = state.pop('score', None)

        with transaction.atomic():
            user = User(username=name, email='{}@example.com'.format(name))
            user.save()
            profile = UserProfile(user=user, name=name)
            profile.save()
            if make_state:
                module = StudentModule(
                    module_state_key=block.location,
                    student=user,
                    course_id=self.course_id,
                    state=json.dumps(state))
                module.save()

            anonymous_id = anonymous_id_for_user(user, self.course_id)
            item = StudentItem(
                student_id=anonymous_id,
                course_id=self.course_id,
                item_id=block.block_id,
                item_type='sga')
            item.save()

            if answer:
                student_id = block.get_student_item_dict(anonymous_id)
                submission = submissions_api.create_submission(student_id, answer)
                if score is not None:
                    submissions_api.set_score(
                        submission['uuid'], score, block.max_score())
            else:
                submission = None

            self.addCleanup(item.delete)
            self.addCleanup(profile.delete)
            self.addCleanup(user.delete)

            if make_state:
                self.addCleanup(module.delete)
                return {
                    'module': module,
                    'item': item,
                    'submission': submission
                }

            return {
                'item': item,
                'submission': submission
            }
Exemple #10
0
def do_create_account_no_registration(data):
    """
    Given cleaned post variables, create the User and UserProfile objects, as well as the
    registration for this user.

    Returns a tuple (User, UserProfile, Registration).

    Note: this function is also used for creating test users.
    """
    # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation

    proposed_username = data["username"]
    user = User(username=proposed_username,
                email=data["phone_number"] +
                settings.DEFAULT_EMAIL_ACCOUNT_DOMAIN,
                is_active=True)
    log.warning("phone: " + data["phone_number"])
    password = normalize_password(data["password"])
    user.set_password(password)
    registration = Registration()
    try:
        with transaction.atomic():
            user.save()
    except IntegrityError:
        # Figure out the cause of the integrity error
        # TODO duplicate email is already handled by form.errors above as a ValidationError.
        # The checks for duplicate email/username should occur in the same place with an
        # AccountValidationError and a consistent user message returned (i.e. both should
        # return "It looks like {username} belongs to an existing account. Try again with a
        # different username.")
        if username_exists_or_retired(user.username):
            raise AccountValidationError(
                USERNAME_EXISTS_MSG_FMT.format(username=proposed_username),
                field="username")
        elif email_exists_or_retired(user.email):
            raise AccountValidationError(_(
                "An account with the Email '{email}' already exists.").format(
                    email=user.email),
                                         field="email")
        else:
            raise

    registration.register(user)
    profile_fields = [
        "name", "level_of_education", "gender", "mailing_address", "city",
        "country", "goals", "year_of_birth", "phone_number",
        "web_accelerator_name", "web_accelerator_link"
    ]
    profile = UserProfile(user=user,
                          **{key: data.get(key)
                             for key in profile_fields})
    profile.save()
    # except Exception:
    #     log.exception("UserProfile creation failed for user {id}.".format(id=user.id))
    #     raise
    log.warning("Testing the process to register {id}".format(id=user.id))
    return user, profile
Exemple #11
0
def import_user_submit(request):
    message = {}
    if request.method == "POST":
        f = request.FILES["file"]
        try:
            count_success = 0
            count_exist = 0
            # --- THIS FAILS ON SING COLUMN CVS ---
            # dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,")
            # f.seek(0)
            # r=csv.reader(f,dialect)
            r = csv.reader(f, delimiter="\t", quotechar="|", quoting=csv.QUOTE_MINIMAL)
            rl = []
            rl.extend(r)
            cohort_id = request.POST.get("cohort_id")
            cohort = Cohort.objects.get(id=cohort_id)
            if cohort.licences < UserProfile.objects.filter(cohort_id=cohort_id).count() + len(rl):
                raise Exception("Licences limit exceeded")
            for line in rl:
                exist = validate_user_cvs_line(line)
                # if(exist):
                #     raise Exception("An user already exists, or duplicate lines.")
                email = line[USER_CVS_COL_EMAIL]
                import random

                username = "".join(random.sample("abcdefg&#%^*f1234567890", 20))
                user = User(username=username, email=email, is_active=True)
                user.set_password(username)
                user.save()
                registration = Registration()
                registration.register(user)
                profile = UserProfile(user=user)
                # profile.transaction_id=transaction_id
                # profile.email=email
                # profile.username=username
                profile.cohort_id = cohort_id
                profile.subscription_status = "Imported"
                profile.save()
                # reg = Registration.objects.get(user=user)
                # d = {'name': profile.name, 'key': reg.activation_key}
                # subject = render_to_string('emails/activation_email_subject.txt', d)
                # subject = ''.join(subject.splitlines())
                # message = render_to_string('emails/activation_email.txt', d)
            db.transaction.commit()
            message = {
                "success": True,
                "message": "Success! %s users imported." % (count_success),
                "count_exist": count_exist,
                "count_success": count_success,
            }
        except Exception as e:
            db.transaction.rollback()
            message = {
                "success": False,
                "error": "Import error: %s. At cvs line: %s, Nobody imported." % (e, count_success + 1),
            }
    return HttpResponse(json.dumps(message))
Exemple #12
0
def _do_create_account(post_vars):
    """
    Given cleaned post variables, create the User and UserProfile objects, as well as the
    registration for this user.

    Returns a tuple (User, UserProfile, Registration).

    Note: this function is also used for creating test users.
    """
    user = User(username=post_vars['username'],
                email=post_vars['email'],
                is_active=False)
    user.set_password(post_vars['password'])
    registration = Registration()
    # TODO: Rearrange so that if part of the process fails, the whole process fails.
    # Right now, we can have e.g. no registration e-mail sent out and a zombie
    # account
    try:
        user.save()
    except IntegrityError:
        js = {'success': False}
        # Figure out the cause of the integrity error
        if len(User.objects.filter(username=post_vars['username'])) > 0:
            js['value'] = "An account with the Public Username  '" + post_vars[
                'username'] + "' already exists."
            js['field'] = 'username'
            return HttpResponse(json.dumps(js))

        if len(User.objects.filter(email=post_vars['email'])) > 0:
            js['value'] = "An account with the Email '" + post_vars[
                'email'] + "' already exists."
            js['field'] = 'email'
            return HttpResponse(json.dumps(js))

        raise

    registration.register(user)

    profile = UserProfile(user=user)
    profile.name = post_vars['name']
    profile.level_of_education = post_vars.get('level_of_education')
    profile.gender = post_vars.get('gender')
    profile.mailing_address = post_vars.get('mailing_address')
    profile.goals = post_vars.get('goals')

    try:
        profile.year_of_birth = int(post_vars['year_of_birth'])
    except (ValueError, KeyError):
        # If they give us garbage, just ignore it instead
        # of asking them to put an integer.
        profile.year_of_birth = None
    try:
        profile.save()
    except Exception:
        log.exception(
            "UserProfile creation failed for user {0}.".format(user.id))
    return (user, profile, registration)
Exemple #13
0
def new_user_social(request):
    if not request.user.is_authenticated():

        return HttpResponseRedirect('signin')
    try:
        userprofile = UserProfile(user=request.user)
        userprofile.save()
    except:
        pass

    return index(request)
Exemple #14
0
def new_user_social(request):
    if not request.user.is_authenticated():

        return HttpResponseRedirect('signin')
    try:
        userprofile=UserProfile(user=request.user)
        userprofile.save()
    except:
        pass

    return index(request)
Exemple #15
0
def new_user_social(request):
    if not request.user.is_authenticated():

        return HttpResponseRedirect('signin')
    try:
        userprofile=UserProfile(user=request.user)
        userprofile.save()
    except:
        return JsonResponse({"error": _("malformed JSON")}, 400)

    return HttpResponseRedirect('howitworks')
Exemple #16
0
def create_user(username,password,email,name):
        user = User(username=username,
                email=email,
                is_active=True,
                )
        user.set_password(password)
        user.save()
        registration = Registration()
        registration.register(user)
        profile = UserProfile(user=user)
        profile.name = name
        profile.save()
def create_user(username, password, email, name):
    user = User(
        username=username,
        email=email,
        is_active=True,
    )
    user.set_password(password)
    user.save()
    registration = Registration()
    registration.register(user)
    profile = UserProfile(user=user)
    profile.name = name
    profile.save()
def user_submit(request):
    if not request.user.is_authenticated:
        raise Http404
    try:
        if request.POST.get('id'):
            profile=UserProfile.objects.get(user_id=request.POST['id'])
            user=User.objects.get(id=request.POST['id'])
        else:
            profile=UserProfile()
            user=User()

        if request.POST['subscription_status']=='Registered':
            user.is_active=True
        else:
            user.is_active=False

        user.email=request.POST['email']
        user.save()

        profile.user_id=user.id
        profile.school_id=request.POST['school_id']
        profile.cohort_id=request.POST['cohort_id']
        profile.district_id=request.POST['district_id']
        profile.subscription_status=request.POST['subscription_status']
        profile.save()

    except Exception as e:
        db.transaction.rollback()
        return HttpResponse(json.dumps({'success': False,'error':'%s' % e}))
    return HttpResponse(json.dumps({'success': True}))
    def setUp(self):
        self.reset_setting_cache_variables()
        super(SelfPacedDateOverrideTest, self).setUp()

        SelfPacedConfiguration(enabled=True).save()

        self.non_staff_user, __ = self.create_non_staff_user()

        # create a UserProfile for user so user doesn't look like sneak_peek user
        nonstaff_user_profile = UserProfile(user=self.non_staff_user)
        nonstaff_user_profile.save()

        self.now = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
        self.future = self.now + datetime.timedelta(days=30)
Exemple #20
0
    def setUp(self):  # pylint: disable=E7601
        """
        Create one user and save it to the database
        """
        self.user = UserFactory.build(username='******', email='*****@*****.**')
        self.user.set_password('test_password')
        self.user.save()
        profile = UserProfile(user=self.user)
        profile.city = 'Boston'
        profile.save()

        # Create the test client
        cache.clear()
        self.session_url = '/api/server/sessions'
Exemple #21
0
    def setUp(self):
        self.reset_setting_cache_variables()
        super(SelfPacedDateOverrideTest, self).setUp()

        SelfPacedConfiguration(enabled=True).save()

        self.non_staff_user, __ = self.create_non_staff_user()

        # create a UserProfile for user so user doesn't look like sneak_peek user
        nonstaff_user_profile = UserProfile(user=self.non_staff_user)
        nonstaff_user_profile.save()

        self.now = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
        self.future = self.now + datetime.timedelta(days=30)
    def setUp(self):
        """
        Create one user and save it to the database
        """
        self.user = UserFactory.build(username='******', email='*****@*****.**')
        self.user.set_password('test_password')
        self.user.save()
        profile = UserProfile(user=self.user)
        profile.city = 'Boston'
        profile.save()

        # Create the test client
        self.client = Client()
        cache.clear()
        self.session_url = '/api/server/sessions'
Exemple #23
0
def get_feedback_form_context(request):
    """
    Extract the submitted form fields to be used as a context for
    feedback submission.
    """
    context = {}

    context["subject"] = request.POST["subject"]
    context["details"] = request.POST["details"]
    context["tags"] = dict(
        [(tag, request.POST[tag]) for tag in ["issue_type", "course_id"] if request.POST.get(tag)]
    )

    context["additional_info"] = {}

    if UserProfile.has_registered(request.user):
        context["realname"] = request.user.profile.name
        context["email"] = request.user.email
        context["additional_info"]["username"] = request.user.username
    else:
        context["realname"] = request.POST["name"]
        context["email"] = request.POST["email"]

    for header, pretty in [("HTTP_REFERER", "Page"), ("HTTP_USER_AGENT", "Browser"), ("REMOTE_ADDR", "Client IP"),
                           ("SERVER_NAME", "Host")]:
        context["additional_info"][pretty] = request.META.get(header)

    context["support_email"] = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)

    return context
Exemple #24
0
    def can_load():
        """
        NOTE: This does not check that the student is enrolled in the course
        that contains this module.  We may or may not want to allow non-enrolled
        students to see modules.  If not, views should check the course, so we
        don't have to hit the enrollments table on every module load.
        """
        # Stanford Sneak Peek permissions
        if user.is_authenticated():
            if not UserProfile.has_registered(user):
                if not _can_load_descriptor_nonregistered(descriptor):
                    return ACCESS_DENIED
        # / Stanford Sneak Peek permissions

        if _has_staff_access_to_descriptor(user, descriptor, course_key):
            return ACCESS_GRANTED

        # if the user has staff access, they can load the module so this code doesn't need to run
        return (_visible_to_nonstaff_users(descriptor)
                and _can_access_descriptor_with_milestones(
                    user, descriptor, course_key)
                and _has_group_access(descriptor, user, course_key)
                and (_has_detached_class_tag(descriptor)
                     or _can_access_descriptor_with_start_date(
                         user, descriptor, course_key)))
Exemple #25
0
    def can_load():
        """
        NOTE: This does not check that the student is enrolled in the course
        that contains this module.  We may or may not want to allow non-enrolled
        students to see modules.  If not, views should check the course, so we
        don't have to hit the enrollments table on every module load.
        """
        if user.is_authenticated():
            if not UserProfile.has_registered(user):
                if not _can_load_descriptor_nonregistered(descriptor):
                    return ACCESS_DENIED

        # If the user (or the role the user is currently masquerading as) does not have
        # access to this content, then deny access. The problem with calling _has_staff_access_to_descriptor
        # before this method is that _has_staff_access_to_descriptor short-circuits and returns True
        # for staff users in preview mode.
        if not _has_group_access(descriptor, user, course_key):
            return ACCESS_DENIED

        # If the user has staff access, they can load the module and checks below are not needed.
        if _has_staff_access_to_descriptor(user, descriptor, course_key):
            return ACCESS_GRANTED

        return (_visible_to_nonstaff_users(descriptor)
                and _can_access_descriptor_with_milestones(
                    user, descriptor, course_key)
                and (_has_detached_class_tag(descriptor)
                     or _can_access_descriptor_with_start_date(
                         user, descriptor, course_key)))
Exemple #26
0
def get_course_tab_list(request, course):
    """
    Retrieves the course tab list from xmodule.tabs and manipulates the set as necessary
    """
    user = request.user
    is_user_enrolled = user.is_authenticated() and CourseEnrollment.is_enrolled(user, course.id)
    xmodule_tab_list = CourseTabList.iterate_displayable(
        course,
        user=user,
        settings=settings,
        is_user_authenticated=user.is_authenticated(),
        is_user_staff=has_access(user, 'staff', course, course.id),
        is_user_enrolled=is_user_enrolled,
        is_user_sneakpeek=not UserProfile.has_registered(user),
    )

    # Now that we've loaded the tabs for this course, perform the Entrance Exam work.
    # If the user has to take an entrance exam, we'll need to hide away all but the
    # "Courseware" tab. The tab is then renamed as "Entrance Exam".
    course_tab_list = []
    must_complete_ee = user_must_complete_entrance_exam(request, user, course)
    for tab in xmodule_tab_list:
        if must_complete_ee:
            # Hide all of the tabs except for 'Courseware'
            # Rename 'Courseware' tab to 'Entrance Exam'
            if tab.type is not 'courseware':
                continue
            tab.name = _("Entrance Exam")
        course_tab_list.append(tab)

    # Add in any dynamic tabs, i.e. those that are not persisted
    course_tab_list += _get_dynamic_tabs(course, user)
    return course_tab_list
Exemple #27
0
def get_feedback_form_context(request):
    """
    Extract the submitted form fields to be used as a context for
    feedback submission.
    """
    context = {}

    context["subject"] = request.POST["subject"]
    context["details"] = request.POST["details"]
    context["tags"] = dict(
        [(tag, request.POST[tag]) for tag in ["issue_type", "course_id"] if tag in request.POST]
    )

    context["additional_info"] = {}

    if UserProfile.has_registered(request.user):
        context["realname"] = request.user.profile.name
        context["email"] = request.user.email
        context["additional_info"]["username"] = request.user.username
    else:
        context["realname"] = request.POST["name"]
        context["email"] = request.POST["email"]

    for header, pretty in [("HTTP_REFERER", "Page"), ("HTTP_USER_AGENT", "Browser"), ("REMOTE_ADDR", "Client IP"),
                           ("SERVER_NAME", "Host")]:
        context["additional_info"][pretty] = request.META.get(header)

    context["support_email"] = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)

    return context
Exemple #28
0
    def can_load():
        """
        NOTE: This does not check that the student is enrolled in the course
        that contains this module.  We may or may not want to allow non-enrolled
        students to see modules.  If not, views should check the course, so we
        don't have to hit the enrollments table on every module load.
        """
        if user.is_authenticated():
            if not UserProfile.has_registered(user):
                if not _can_load_descriptor_nonregistered(descriptor):
                    return ACCESS_DENIED
        response = (
            _visible_to_nonstaff_users(descriptor)
            and _has_group_access(descriptor, user, course_key)
            and
            (
                _has_detached_class_tag(descriptor)
                or _can_access_descriptor_with_start_date(user, descriptor, course_key)
            )
        )

        return (
            ACCESS_GRANTED if (response or _has_staff_access_to_descriptor(user, descriptor, course_key))
            else response
        )
Exemple #29
0
    def can_load():
        """
        NOTE: This does not check that the student is enrolled in the course
        that contains this module.  We may or may not want to allow non-enrolled
        students to see modules.  If not, views should check the course, so we
        don't have to hit the enrollments table on every module load.
        """
        # Stanford Sneak Peek permissions
        if user.is_authenticated():
            if not UserProfile.has_registered(user):
                if not _can_load_descriptor_nonregistered(descriptor):
                    return ACCESS_DENIED
        # / Stanford Sneak Peek permissions

        if _has_staff_access_to_descriptor(user, descriptor, course_key):
            return ACCESS_GRANTED

        # if the user has staff access, they can load the module so this code doesn't need to run
        return (
            _visible_to_nonstaff_users(descriptor) and
            _can_access_descriptor_with_milestones(user, descriptor, course_key) and
            _has_group_access(descriptor, user, course_key) and
            (
                _has_detached_class_tag(descriptor) or
                _can_access_descriptor_with_start_date(user, descriptor, course_key)
            )
        )
Exemple #30
0
def get_course_tab_list(course, user):
    """
    Retrieves the course tab list from xmodule.tabs and manipulates the set as necessary
    """
    user_is_enrolled = user.is_authenticated() and CourseEnrollment.is_enrolled(user, course.id)
    xmodule_tab_list = CourseTabList.iterate_displayable(
        course,
        settings,
        user.is_authenticated(),
        has_access(user, 'staff', course, course.id),
        user_is_enrolled,
        not UserProfile.has_registered(user),
    )

    # Now that we've loaded the tabs for this course, perform the Entrance Exam work
    # If the user has to take an entrance exam, we'll need to hide away all of the tabs
    # except for the Courseware and Instructor tabs (latter is only viewed if applicable)
    # We don't have access to the true request object in this context, but we can use a mock
    request = RequestFactory().request()
    request.user = user
    course_tab_list = []
    for tab in xmodule_tab_list:
        if user_must_complete_entrance_exam(request, user, course):
            # Hide all of the tabs except for 'Courseware' and 'Instructor'
            # Rename 'Courseware' tab to 'Entrance Exam'
            if tab.type not in ['courseware', 'instructor']:
                continue
            if tab.type == 'courseware':
                tab.name = _("Entrance Exam")
        course_tab_list.append(tab)
    return course_tab_list
Exemple #31
0
def create_user_from_oauth(strategy, details, user, is_new, *args, **kwargs):
    if is_new:
        profile = UserProfile(user=user)
        profile.name = details.get('fullname')

        try:
            profile.save()
        except Exception:
            log.error("UserProfile creation failed for user {id}.".format(id=user.id))
            raise

        ceas = CourseEnrollmentAllowed.objects.filter(email=user.email)
        for cea in ceas:
            if cea.auto_enroll:
                CourseEnrollment.enroll(user, cea.course_id)

        create_comments_service_user(user)
Exemple #32
0
    def make_student_module(self, block, name, **state):
        user = User(username=name)
        user.save()
        profile = UserProfile(user=user, name=name)
        profile.save()
        module = StudentModule(
            module_state_key=block.location,
            student=user,
            course_id=self.course_id,
            state=json.dumps(state))
        module.save()

        self.addCleanup(profile.delete)
        self.addCleanup(module.delete)
        self.addCleanup(user.delete)

        return module
Exemple #33
0
    def make_student_module(self, block, name, **state):
        user = User(username=name)
        user.save()
        profile = UserProfile(user=user, name=name)
        profile.save()
        module = StudentModule(
            module_state_key=block.location,
            student=user,
            course_id=self.course_id,
            state=json.dumps(state))
        module.save()

        self.addCleanup(profile.delete)
        self.addCleanup(module.delete)
        self.addCleanup(user.delete)

        return module
Exemple #34
0
    def make_student(self, block, name, **state):
        answer = {}
        for key in ('sha1', 'mimetype', 'filename'):
            if key in state:
                answer[key] = state.pop(key)
        score = state.pop('score', None)

        user = User(username=name)
        user.save()
        profile = UserProfile(user=user, name=name)
        profile.save()
        module = StudentModule(
            module_state_key=block.location,
            student=user,
            course_id=self.course_id,
            state=json.dumps(state))
        module.save()

        anonymous_id = anonymous_id_for_user(user, self.course_id)
        item = StudentItem(
            student_id=anonymous_id,
            course_id=self.course_id,
            item_id=block.block_id,
            item_type='sga')
        item.save()

        if answer:
            student_id = block.student_submission_id(anonymous_id)
            submission = submissions_api.create_submission(student_id, answer)
            if score is not None:
                submissions_api.set_score(
                    submission['uuid'], score, block.max_score())
        else:
            submission = None

        self.addCleanup(item.delete)
        self.addCleanup(profile.delete)
        self.addCleanup(module.delete)
        self.addCleanup(user.delete)

        return {
            'module': module,
            'item': item,
            'submission': submission,
        }
Exemple #35
0
 def can_load_forum():
     """
     Can this user access the forums in this course?
     """
     return (
         can_load()
         and
         UserProfile.has_registered(user)
     )
Exemple #36
0
 def process_request(self, request):
     """
     Log out all sneakpeek users and redirect the same URL
     """
     if request.user.is_anonymous():
         return None
     if UserProfile.has_registered(request.user):
         return None
     logout(request)
     return redirect(request.get_full_path())
Exemple #37
0
def cas_login(request, next_page=None, required=False):
    """
        Uses django_cas for authentication.
        CAS is a common authentcation method pioneered by Yale.
        See http://en.wikipedia.org/wiki/Central_Authentication_Service

        Does normal CAS login then generates user_profile if nonexistent,
        and if login was successful.  We assume that user details are
        maintained by the central service, and thus an empty user profile
        is appropriate.
    """

    ret = django_cas_login(request, next_page, required)

    if request.user.is_authenticated():
        user = request.user
        if not UserProfile.objects.filter(user=user):
            user_profile = UserProfile(name=user.username, user=user)
            user_profile.save()

    return ret
Exemple #38
0
 def can_load_forum():
     """
     Can this user access the forums in this course?
     """
     return (
         can_load() and
         UserProfile.has_registered(user) and
         (
             CourseEnrollment.is_enrolled(user, course.id) or
             _has_staff_access_to_descriptor(user, course, course.id)
         )
     )
Exemple #39
0
def login_and_registration_form(request, initial_mode="login"):
    """Render the combined login/registration form, defaulting to login

    This relies on the JS to asynchronously load the actual form from
    the user_api.

    Keyword Args:
        initial_mode (string): Either "login" or "register".

    """
    # If we're already logged in, redirect to the dashboard
    if UserProfile.has_registered(request.user):
        return redirect(reverse("dashboard"))

    # Retrieve the form descriptions from the user API
    form_descriptions = _get_form_descriptions(request)

    # If this is a microsite, revert to the old login/registration pages.
    # We need to do this for now to support existing themes.
    if microsite.is_request_in_microsite():
        if initial_mode == "login":
            return old_login_view(request)
        elif initial_mode == "register":
            return old_register_view(request)

    # Allow external auth to intercept and handle the request
    ext_auth_response = _external_auth_intercept(request, initial_mode)
    if ext_auth_response is not None:
        return ext_auth_response

    # Otherwise, render the combined login/registration page
    context = {
        "disable_courseware_js": True,
        "initial_mode": initial_mode,
        "third_party_auth": json.dumps(_third_party_auth_context(request)),
        "platform_name": settings.PLATFORM_NAME,
        "account_name": settings.ACCOUNT_NAME,
        "responsive": True,
        # Include form descriptions retrieved from the user API.
        # We could have the JS client make these requests directly,
        # but we include them in the initial page load to avoid
        # the additional round-trip to the server.
        "login_form_desc": form_descriptions["login"],
        "registration_form_desc": form_descriptions["registration"],
        "password_reset_form_desc": form_descriptions["password_reset"],
        # We need to pass these parameters so that the header's
        # "Sign In" button preserves the querystring params.
        "enrollment_action": request.GET.get("enrollment_action"),
        "course_id": request.GET.get("course_id"),
        "course_mode": request.GET.get("course_mode"),
    }

    return render_to_response("student_account/login_and_register.html", context)
Exemple #40
0
def cas_login(request, next_page=None, required=False):
    """
        Uses django_cas for authentication.
        CAS is a common authentcation method pioneered by Yale.
        See http://en.wikipedia.org/wiki/Central_Authentication_Service

        Does normal CAS login then generates user_profile if nonexistent,
        and if login was successful.  We assume that user details are
        maintained by the central service, and thus an empty user profile
        is appropriate.
    """

    ret = django_cas_login(request, next_page, required)

    if request.user.is_authenticated():
        user = request.user
        if not UserProfile.objects.filter(user=user):
            user_profile = UserProfile(name=user.username, user=user)
            user_profile.save()

    return ret
Exemple #41
0
    def create_user_and_user_profile(self, email, username, password,
                                     custom_field, complete_name, first_name,
                                     last_name):
        """
        Create a new user, add a new Registration instance for letting user verify its identity and create a user profile.
        :param email: user's email address
        :param username: user's username
        :param name: user's name
        :param country: user's country
        :param password: user's password
        :return: User instance of the new user.
        """
        user = User(
            username=username,
            email=email,
            is_active=True,
            first_name=first_name,
            last_name=last_name,
        )
        user.set_password(password)
        user.save()
        registration = Registration()
        registration.register(user)
        """
        reg = Registration()
        reg.register(user)
        """
        #user.save()
        profile = UserProfile(user=user)
        profile.custom_field = json.dumps(custom_field)
        profile.name = complete_name
        profile.save()

        return user
def import_user(u):
    user_info = u["u"]
    up_info = u["up"]

    # HACK to handle dates
    user_info["last_login"] = dateutil.parser.parse(user_info["last_login"])
    user_info["date_joined"] = dateutil.parser.parse(user_info["date_joined"])

    user_keys = [
        "id",
        "username",
        "email",
        "password",
        "is_staff",
        "is_active",
        "is_superuser",
        "last_login",
        "date_joined",
        "password",
    ]
    up_keys = ["language", "location", "meta", "name", "id", "user_id"]

    u = User()
    for key in user_keys:
        u.__setattr__(key, user_info[key])
    u.save()

    up = UserProfile()
    up.user = u
    for key in up_keys:
        up.__setattr__(key, up_info[key])
    up.save()
    def create_user(self, uname, name, password=None):
        """ Creates a user """

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

        msg = u''
        if not password:
            return _('Password must be supplied')

        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 += _(u'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()

        msg += _(u'User {user} created successfully!').format(user=user)
        return msg
    def create_user(self, uname, name, password=None):
        """ Creates a user """

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

        msg = u''
        if not password:
            return _('Password must be supplied')

        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 += _(u'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()

        msg += _(u'User {user} created successfully!').format(user=user)
        return msg
Exemple #45
0
def update_profile_info(request):
    """
    """
    # Get the user

    data = request.POST.copy()
    user = request.user

    post_registration_fields = [('gender', str), ('country', str),
                                ('year_of_birth', int)]

    try:
        user_profile = UserProfile.objects.get(user=user)
        user_has_profile = True
    except UserProfile.DoesNotExist:
        # Handle when no profile for the user, create a new one
        user_profile = UserProfile(user=user)
        user_has_profile = False

    for field in post_registration_fields:
        field_name = field[0]
        field_type = field[1]

        value = field_type(data.get(field_name))

        if value:
            setattr(user_profile, field_name, value)

    try:
        user_profile.save(update_fields=list(
            field[0] for field in post_registration_fields
        ) if user_has_profile else None)
        return JsonResponse({"is_success": True}, status=200)
    except (DatabaseError, ValidationError, TypeError) as e:
        log.error('Failed to save post auth data for {user}, exception is {e}'.
                  format(user=user.username, e=e))

    return JsonResponse({"is_success": False}, status=400)
    def process_request(self, request):
        """
        logs out all sneakpeek users and then retries (redirects) the same URL
        """
        #Do nothing with AnonymousUser
        if request.user.is_anonymous():
            return None

        #Do nothing with non-sneakpeek user
        if UserProfile.has_registered(request.user):
            return None

        logout(request)
        return redirect(request.get_full_path())
Exemple #47
0
def create_new_user(name=''):
    """
    new user
    :return:
    """
    def create_():
        password = TIANYUYUN_PASSWORD
        username = gen_union_username()
        email = '*****@*****.**' % username
        user = User(
            username=username,
            email=email,
            is_active=True
        )
        user.set_password(password)
        try:
            user.save()
        except:
            return None
        return user

    user = create_()
    if not user:
        while True:
            user = create_()
            if user:
                break
    # TODO UserProfile
    try:
        from student.models import UserProfile
        profile_name = name or 'someone'
        profile = UserProfile(user=user, name='someone')
        profile.save()
    except:
        pass

    return user
Exemple #48
0
def index(request):
    '''
    Redirects to main page -- info page if user authenticated, or marketing if not
    '''

    if UserProfile.has_registered(request.user):
        # Only redirect to dashboard if user has
        # courses in his/her dashboard. Otherwise UX is a bit cryptic.
        # In this case, we want to have the user stay on a course catalog
        # page to make it easier to browse for courses (and register)
        if configuration_helpers.get_value(
                'ALWAYS_REDIRECT_HOMEPAGE_TO_DASHBOARD_FOR_AUTHENTICATED_USER',
                settings.FEATURES.get('ALWAYS_REDIRECT_HOMEPAGE_TO_DASHBOARD_FOR_AUTHENTICATED_USER', True)):
            return redirect(reverse('dashboard'))

    if settings.FEATURES.get('AUTH_USE_CERTIFICATES'):
        from openedx.core.djangoapps.external_auth.views import ssl_login
        # Set next URL to dashboard if it isn't set to avoid
        # caching a redirect to / that causes a redirect loop on logout
        if not request.GET.get('next'):
            req_new = request.GET.copy()
            req_new['next'] = reverse('dashboard')
            request.GET = req_new
        return ssl_login(request)

    enable_mktg_site = configuration_helpers.get_value(
        'ENABLE_MKTG_SITE',
        settings.FEATURES.get('ENABLE_MKTG_SITE', False)
    )

    if enable_mktg_site:
        marketing_urls = configuration_helpers.get_value(
            'MKTG_URLS',
            settings.MKTG_URLS
        )
        return redirect(marketing_urls.get('ROOT'))

    domain = request.META.get('HTTP_HOST')

    # keep specialized logic for Edge until we can migrate over Edge to fully use
    # configuration.
    if domain and 'edge.edx.org' in domain:
        return redirect(reverse("signin_user"))

    #  we do not expect this case to be reached in cases where
    #  marketing and edge are enabled
    return student.views.index(request, user=request.user)
    def test_invalidate_cache_user_profile_country_updated(self):

        country = 'us'
        self.profile.country = country
        self.profile.save()

        cache_key = UserProfile.country_cache_key_name(self.user.id)
        self.assertIsNone(cache.get(cache_key))

        cache.set(cache_key, self.profile.country)
        self.assertEqual(cache.get(cache_key), country)

        country = 'bd'
        self.profile.country = country
        self.profile.save()

        self.assertNotEqual(cache.get(cache_key), country)
        self.assertIsNone(cache.get(cache_key))
Exemple #50
0
def get_course_tab_list(request, course):
    """
    Retrieves the course tab list from xmodule.tabs and manipulates the set as necessary
    """
    user = request.user
    is_user_enrolled = user.is_authenticated(
    ) and CourseEnrollment.is_enrolled(user, course.id)
    xmodule_tab_list = CourseTabList.iterate_displayable(
        course,
        user=user,
        settings=settings,
        is_user_authenticated=user.is_authenticated(),
        is_user_staff=has_access(user, 'staff', course, course.id),
        is_user_enrolled=is_user_enrolled,
        is_user_sneakpeek=not UserProfile.has_registered(user),
    )

    # Now that we've loaded the tabs for this course, perform the Entrance Exam work.
    # If the user has to take an entrance exam, we'll need to hide away all but the
    # "Courseware" tab. The tab is then renamed as "Entrance Exam".
    course_tab_list = []
    must_complete_ee = not user_can_skip_entrance_exam(user, course)
    for tab in xmodule_tab_list:
        if must_complete_ee:
            # Hide all of the tabs except for 'Courseware'
            # Rename 'Courseware' tab to 'Entrance Exam'
            if tab.type != 'courseware':
                continue
            tab.name = _("Entrance Exam")
        if tab.type == 'static_tab' and tab.course_staff_only and \
                not bool(user and has_access(user, 'staff', course, course.id)):
            continue
        course_tab_list.append(tab)

    # Add in any dynamic tabs, i.e. those that are not persisted
    course_tab_list += _get_dynamic_tabs(course, user)
    return course_tab_list
Exemple #51
0
def import_user(u):
    user_info = u['u']
    up_info = u['up']

    # HACK to handle dates
    user_info['last_login'] = dateutil.parser.parse(user_info['last_login'])
    user_info['date_joined'] = dateutil.parser.parse(user_info['date_joined'])

    user_keys = ['id', 'username', 'email', 'password', 'is_staff',
                 'is_active', 'is_superuser', 'last_login', 'date_joined',
                 'password']
    up_keys = ['language', 'location', 'meta', 'name', 'id', 'user_id']

    u = User()
    for key in user_keys:
        u.__setattr__(key, user_info[key])
    u.save()

    up = UserProfile()
    up.user = u
    for key in up_keys:
        up.__setattr__(key, up_info[key])
    up.save()
Exemple #52
0
def do_create_account(form, custom_form=None):
    """
    Given cleaned post variables, create the User and UserProfile objects, as well as the
    registration for this user.

    Returns a tuple (User, UserProfile, Registration).

    Note: this function is also used for creating test users.
    """
    # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation
    if not configuration_helpers.get_value(
            'ALLOW_PUBLIC_ACCOUNT_CREATION',
            settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True)
    ):
        raise PermissionDenied()

    errors = {}
    errors.update(form.errors)
    if custom_form:
        errors.update(custom_form.errors)

    if errors:
        raise ValidationError(errors)

    proposed_username = form.cleaned_data["username"]
    user = User(
        username=proposed_username,
        email=form.cleaned_data["email"],
        is_active=False
    )
    password = normalize_password(form.cleaned_data["password"])
    user.set_password(password)
    registration = Registration()

    # TODO: Rearrange so that if part of the process fails, the whole process fails.
    # Right now, we can have e.g. no registration e-mail sent out and a zombie account
    try:
        with transaction.atomic():
            user.save()
            if custom_form:
                custom_model = custom_form.save(commit=False)
                custom_model.user = user
                custom_model.save()
    except IntegrityError:
        # Figure out the cause of the integrity error
        # TODO duplicate email is already handled by form.errors above as a ValidationError.
        # The checks for duplicate email/username should occur in the same place with an
        # AccountValidationError and a consistent user message returned (i.e. both should
        # return "It looks like {username} belongs to an existing account. Try again with a
        # different username.")
        if username_exists_or_retired(user.username):
            raise AccountValidationError(
                USERNAME_EXISTS_MSG_FMT.format(username=proposed_username),
                field="username"
            )
        elif email_exists_or_retired(user.email):
            raise AccountValidationError(
                _("An account with the Email '{email}' already exists.").format(email=user.email),
                field="email"
            )
        else:
            raise

    registration.register(user)

    profile_fields = [
        "name", "level_of_education", "gender", "mailing_address", "city", "country", "goals",
        "year_of_birth"
    ]
    profile = UserProfile(
        user=user,
        **{key: form.cleaned_data.get(key) for key in profile_fields}
    )
    extended_profile = form.cleaned_extended_profile
    if extended_profile:
        profile.meta = json.dumps(extended_profile)
    try:
        profile.save()
    except Exception:
        log.exception("UserProfile creation failed for user {id}.".format(id=user.id))
        raise

    return user, profile, registration
Exemple #53
0
    def handle(self, *args, **options):

        while True:
            uname = raw_input('username: '******'Create MIT ExternalAuth? [n] ').lower() == 'y':
            email = '*****@*****.**' % 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 email_exists_or_retired(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)
            print "Added %s to group %s" % (user, g)

        print "Done!"
Exemple #54
0
    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)):
                msg += u'{0} @{1}'.format(_('email must end in'), email_domain)
                return msg
            mit_domain = 'ssl:MIT'
            if ExternalAuthMap.objects.filter(external_id=email,
                                              external_domain=mit_domain):
                msg += _('Failed - email {0} already exists as '
                         'external_id').format(email)
                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 {0}, '
                     'IntegrityError').format(user)
            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 {0} created successfully!').format(user)
        return msg
Exemple #55
0
def create_account(username, password, email):
    """Create a new user account.

    This will implicitly create an empty profile for the user.

    WARNING: This function does NOT yet implement all the features
    in `student/views.py`.  Until it does, please use this method
    ONLY for tests of the account API, not in production code.
    In particular, these are currently missing:

    * 3rd party auth
    * External auth (shibboleth)
    * Complex password policies (ENFORCE_PASSWORD_POLICY)

    In addition, we assume that some functionality is handled
    at higher layers:

    * Analytics events
    * Activation email
    * Terms of service / honor code checking
    * Recording demographic info (use profile API)
    * Auto-enrollment in courses (if invited via instructor dash)

    Args:
        username (unicode): The username for the new account.
        password (unicode): The user's password.
        email (unicode): The email address associated with the account.

    Returns:
        unicode: an activation key for the account.

    Raises:
        errors.AccountUserAlreadyExists
        errors.AccountUsernameInvalid
        errors.AccountEmailInvalid
        errors.AccountPasswordInvalid
        errors.UserAPIInternalError: the operation failed due to an unexpected error.

    """
    # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation
    if not configuration_helpers.get_value(
            'ALLOW_PUBLIC_ACCOUNT_CREATION',
            settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True)):
        return HttpResponseForbidden(_("Account creation not allowed."))

    if waffle().is_enabled(PREVENT_AUTH_USER_WRITES):
        raise errors.UserAPIInternalError(SYSTEM_MAINTENANCE_MSG)

    # Validate the username, password, and email
    # This will raise an exception if any of these are not in a valid format.
    _validate_username(username)
    _validate_password(password, username)
    _validate_email(email)

    # Create the user account, setting them to "inactive" until they activate their account.
    user = User(username=username, email=email, is_active=False)
    user.set_password(password)

    try:
        user.save()
    except IntegrityError:
        raise errors.AccountUserAlreadyExists

    # Create a registration to track the activation process
    # This implicitly saves the registration.
    registration = Registration()
    registration.register(user)

    # Create an empty user profile with default values
    UserProfile(user=user).save()

    # Return the activation key, which the caller should send to the user
    return registration.activation_key
Exemple #56
0
 def delete_users_country_cache(user):
     cache_key = UserProfile.country_cache_key_name(user.id)
     cache.delete(cache_key)
Exemple #57
0
def create_account(username, password, email):
    """Create a new user account.

    This will implicitly create an empty profile for the user.

    WARNING: This function does NOT yet implement all the features
    in `student/views.py`.  Until it does, please use this method
    ONLY for tests of the account API, not in production code.
    In particular, these are currently missing:

    * 3rd party auth
    * External auth (shibboleth)
    * Complex password policies (ENFORCE_PASSWORD_POLICY)

    In addition, we assume that some functionality is handled
    at higher layers:

    * Analytics events
    * Activation email
    * Terms of service / honor code checking
    * Recording demographic info (use profile API)
    * Auto-enrollment in courses (if invited via instructor dash)

    Args:
        username (unicode): The username for the new account.
        password (unicode): The user's password.
        email (unicode): The email address associated with the account.

    Returns:
        unicode: an activation key for the account.

    Raises:
        AccountUserAlreadyExists
        AccountUsernameInvalid
        AccountEmailInvalid
        AccountPasswordInvalid
        UserAPIInternalError: the operation failed due to an unexpected error.
    """
    # Validate the username, password, and email
    # This will raise an exception if any of these are not in a valid format.
    _validate_username(username)
    _validate_password(password, username)
    _validate_email(email)

    # Create the user account, setting them to "inactive" until they activate their account.
    user = User(username=username, email=email, is_active=False)
    user.set_password(password)

    try:
        user.save()
    except IntegrityError:
        raise AccountUserAlreadyExists

    # Create a registration to track the activation process
    # This implicitly saves the registration.
    registration = Registration()
    registration.register(user)

    # Create an empty user profile with default values
    UserProfile(user=user).save()

    # Return the activation key, which the caller should send to the user
    return registration.activation_key
Exemple #58
0
    def create_user(self,
                    uname,
                    name,
                    is_tempuser,
                    password='******',
                    request=None):
        """ Creates a user (both SSL and regular)"""

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

        msg = u''

        if '@' not in uname:
            msg += _('Email address must contain @')
            return msg
        elif not password:
            msg += _('Password must be supplied if not using certificates')
            return msg

        email = uname
        new_password = password

        try:
            from django.db import transaction
            with transaction.atomic():
                user = User(username=uname, email=email, is_active=True)
                user.set_password(new_password)
                user.save()
        except IntegrityError:
            msg += _('Oops, failed to create user {user}, {error}').format(
                user=uname, error="{} already exist.".format(email))
            return msg

        reg = Registration()
        reg.register(user)

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

        mosouser = MosoUser(user=user, creted_by=request.user)
        mosouser.save()
        msg += _('User {user} created successfully!').format(user=user)

        if is_tempuser:
            try:
                task_result = deactivate_task(user.id)
                if task_result:
                    msg += "<br> Configure Deactivate Task successfully!"
                    print("*" * 50)
                    print("Configure Deactivate Task successfully!")
            except:
                msg += "<br> Failed to Configure Deactivate Task!"
                print("Failed to Configure Deactivate Task!")
        else:
            msg += "<br> Failed to Configure Deactivate Task!"

        return msg