Exemple #1
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 #2
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)
def _get_or_create_oauth_user(strategy, detail, request=None, mobile_client=False, created_on="web"):
    """
    strategy -- strategy obj
    detail -- oauth登录拿到token时的response
    """
    backend = strategy.backend
    _created = False
    uid = get_uid(strategy, detail)
    # weibo新接口uid改名叫做id
    if not uid:
        uid = detail.get("id")
    # weixin
    if backend.name in ("weixin", "weixinapp"):
        weixin_unionid = detail.get("unionid")
        if weixin_unionid:
            weixin_users = UserSocialAuth.objects.filter(weixin_unionid=weixin_unionid).order_by("id")
            weixin_users_count = weixin_users.count()
            # 微信只有一个UserSocialAuth时,使用这个
            if weixin_users_count == 1:
                user = weixin_users[0].user
                user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                return (user, False)
            elif weixin_users_count > 1:
                # 有web则永远返回第一个web用户
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith("web"):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                        return (user, False)
                # 否则返回mobile用户
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith("mobile"):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                        return (user, False)
                # 否则返回weixin app用户(微信服务号活动生成)
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith("app"):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                        return (user, False)
                # 没有第四种逻辑, 但是还是加上吧
                user = weixin_users[0].user
                user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                return (user, False)
    if backend.name == "chinamobile":
        extra_data = backend.extra_data(None, uid, detail, {})
        phone_number = extra_data.get("phone_number", None)
        try:
            user_profile = UserProfile.objects.get(phone_number=phone_number)
            user = user_profile.user
            user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
            return (user, False)
        except:
            pass
    result = social_user(strategy, uid)
    # 已有账户,直接登录
    if result["user"]:
        user = result["user"]
    # 否则创建用户,之后登录
    else:
        user = User()
        user.username = str(uuid.uuid4()).replace("-", "")[:20]
        user.email = None
        # oauth的自动激活
        user.is_active = True
        user.set_unusable_password()
        user.save()
        extra_data = backend.extra_data(user, uid, detail, {})
        profile = UserProfile(user=user)
        nickname = get_validate_nickname(extra_data["username"])
        oauth_nickname = nickname
        # 重名加后缀,最多尝试10次
        MAX_TRY_TIMES = 10
        while MAX_TRY_TIMES:
            try:
                UserProfile.objects.get(nickname=nickname)
                suffix = str(uuid.uuid4().int)[:6]
                nickname = "{}{}".format(oauth_nickname, suffix)
                MAX_TRY_TIMES = MAX_TRY_TIMES - 1
            except UserProfile.DoesNotExist:
                break
        profile.phone_number = extra_data.get("phone_number", None)
        profile.nickname = nickname
        profile.unique_code = profile.get_unique_code()
        if request:
            profile.set_register_extra(request=request, cover_data={"channel": backend.name})
        if extra_data.get("profile_image_url"):
            profile.avatar = extra_data["profile_image_url"]
        if extra_data.get("gender"):
            profile.gender = extra_data["gender"]
        if extra_data.get("year_of_birth"):
            profile.year_of_birth = extra_data["year_of_birth"]
        if backend.name == "chinamobile":
            profile.register_type = "migu"
            profile.register_auto = 1
        profile.save()
        # TODO: AuthAlreadyAssociated
        # 此oauth账号之前已经绑定了学堂在线的账号
        new_associate_user(strategy, uid, user, detail, created_on=created_on)
        _created = True
        # Track this user register event in oauth
        if not mobile_client:  # do not track api client log 2015.5.26
            event_type = (
                "weixinapp.user.register_success" if created_on == "weixinapp" else "oauth.user.register_success"
            )
            # track_log(request, event_type, {
            #     'success': True,
            #     'uid': user.id,
            #     'provider': backend.name,
            # })
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    return (user, _created)
Exemple #4
0
            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 {id}.".format(id=user.id))
    return (user, profile, registration)


@ensure_csrf_cookie
def create_account(request, post_override=None):
    '''
    JSON call to create new edX account.
Exemple #5
0
def register_institute(request, post_override=None):

    """
    JSON call to create new institute.
    """
    js = {'success': False}
    post_vars = post_override if post_override else request.POST
    extra_fields = getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {})

    
    for a in ['name', 'state', 'city']:
        if a not in post_vars:
            js['value'] = _("Error (401 {field}). E-mail us.").format(field=a)
            js['field'] = a
            return JsonResponse(js, status=400)


    required_post_vars = ['name', 'state', 'city', 'pincode', 'address', 'website', 'headName', 'headEmail', 'headMobile', 'rccName', 'rccEmail', 'rccMobile', 'studentIdentity']


    for field_name in required_post_vars:
        if field_name in ('state', 'city'):
           min_length = 1
        else:
           min_length = 2

        if len(post_vars[field_name]) < min_length:
            error_str = {
                'name': _('Name must be minimum of two characters long'),
                'state': _('A state is required'),
                'address': _('Your address is required'),
                'city': _('A city is required'),
		        'pincode' : _('Your Pincode is required'),
                'website' : _('Your website is required'),
                'headName' : _('Head Name must be minimum of two characters long'),
                'headEmail' : _('A properly formatted e-mail is required'),
                'headMobile' : _('Head Mobile must be of 10 digits'),
                'rccName' : _('RCC Name must be minimum of two characters long'),
                'rccEmail' : _('A properly formatted e-mail is required'),
                'rccMobile' : _('RCC Mobile must be of 10 digits'),
                'honor_code': _('Agreeing to the Honor Code is required'),
                'terms_of_service': _('Accepting Terms of Service is required')
            }
            js['value'] = error_str[field_name]
            js['field'] = field_name
            return JsonResponse(js, status=400)
    try:
        validate_email(post_vars['headEmail'])
    except ValidationError:
        js['value'] = _("Valid e-mail is required.").format(field=a)
        js['field'] = 'email'
        return JsonResponse(js, status=400)

    try:
        validate_email(post_vars['rccEmail'])
    except ValidationError:
        js['value'] = _("Valid e-mail is required.").format(field=a)
        js['field'] = 'email'
        return JsonResponse(js, status=400)



    if extra_fields.get('honor_code', 'required') == 'required' and \
            post_vars.get('honor_code', 'false') != u'true':
        js['value'] = _("To enroll, you must follow the honor code.").format(field=a)
        js['field'] = 'honor_code'
        return JsonResponse(js, status=400)


    if extra_fields.get('terms_of_service', 'required') == 'required' and \
            post_vars.get('terms_of_service', 'false') != u'true':
        js['value'] = _("To enroll, you must accept terms of service.").format(field=a)
        js['field'] = 'terms_of_service'
        return JsonResponse(js, status=400)

    
    status=Institute_Status.objects.filter(name="Pending")[0].id 

    institute = Institute_Registration( name=post_vars['name'], state_id=post_vars['state'], city_id=post_vars['city'], pincode=post_vars['pincode'], status_id=status, is_parent=False, address=post_vars['address'], website=post_vars['website'])


    if post_vars['headEmail'] == post_vars['rccEmail']:
            js['value'] = _("Please provide different emails for Head and Coordinator").format(email=post_vars['headEmail'])
            js['field'] = 'email'
            return JsonResponse(js,status=400)


    if len(User.objects.filter(email=str(post_vars['headEmail']))) > 0:
            js = {'success': False}
            js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['headEmail'])
            js['field'] = 'email'
            return JsonResponse(js,status=400)

    if len(User.objects.filter(email=str(post_vars['rccEmail']))) > 0:
            js = {'success': False}
            js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['rccEmail'])
            js['field'] = 'email'
            return JsonResponse(js,status=400)


    try:
        institute.save()
    except IntegrityError as e:
        js = {'success': False}
        
        if len(Institute_Registration.objects.filter(name=post_vars['name'])) > 0:
            js['value'] = _("An Institute with the name '{name}' already exists.").format(name=post_vars['name'])
            js['field'] = 'name'
            return JsonResponse(js,status=400)
        
	
    insti_id= institute.id

    accreditation = request.POST.getlist('accreditation')

    for index in accreditation:
    	acc = Institute_Accreditation(accreditation_id=index , institute_id=insti_id)
    	acc.save()


    headUsername = post_vars['headEmail'].split('@')
    headUsername = GenerateUsername(headUsername[0])

    headPass = uuid.uuid4().hex[0:10]
    
    user = User(username=headUsername,
                email=post_vars['headEmail'],
                is_active=False)
    user.set_password(headPass)
   
    try:
        user.save()
        head_user_object = user
    except IntegrityError as e:
        js = {'success': False}
        # Figure out the cause of the integrity error
        if len(User.objects.filter(email=post_vars['headEmail'])) > 0:
            js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['headEmail'])
            js['field'] = 'email'
            return JsonResponse(js,status=400)

    profile = UserProfile(user=user)
    profile.name = post_vars['headName']
    profile.year_of_birth = None
    person = Person(user=user)
   
    person.mobile = post_vars.get('headMobile')
    person.save()
       
    try:
        profile.save()
    except Exception:
        log.exception("UserProfile creation failed for user {id}.".format(id=user.id))


    head_role_id = Role.objects.filter(name="Institute Head")[0].id


    designation = Institute_Designation(user=user, institute_id=insti_id, role_id=head_role_id, is_approved=False)
    designation.save()




    rccUsername = post_vars['rccEmail'].split('@')
    rccUsername = GenerateUsername(rccUsername[0])

    rccPass = uuid.uuid4().hex[0:10]
    
    user = User(username=rccUsername,
                email=post_vars['rccEmail'],
                is_active=False)
    user.set_password(rccPass)


 
   
   
    try:
        user.save()
        rcc_user_object = user
    except IntegrityError as e:
        js = {'success': False}
        # Figure out the cause of the integrity error
        if len(User.objects.filter(email=post_vars['rccEmail'])) > 0:
            js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['rccEmail'])
            js['field'] = 'email'
            return JsonResponse(js,status=400)

    profile = UserProfile(user=user)
    profile.name = post_vars['rccName']
    profile.year_of_birth = None
    person = Person(user=user)
   
    person.mobile = post_vars.get('rccMobile')
    person.save()
       
    try:
        profile.save()
    except Exception:
        log.exception("UserProfile creation failed for user {id}.".format(id=user.id))


    ic_role_id = Role.objects.filter(name="Institute Coordinator")[0].id
    designation = Institute_Designation(user=user, institute_id=insti_id, role_id=ic_role_id, is_approved=False)
    designation.save()

#identity_name = post_vars.get('studentIdentity')
 #   student_identity = Identity(name=identity_name)
  #  student_identity.save()
    
   # institute_id = Institute_Registration.objects.filter(name=post_vars.get('name'))[0].id
    #identity_id = Identity.objects.filter(name=identity_name)[0].id
    #institute_identity = Institute_Identity(institute_id=institute_id, identity_id=identity_id)
    #institute_identity.save() '''
    

    context = {'name': "test",}

    # composes thank you email
    subject = render_to_string('emails/thankyou_email_subject.txt',context)
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    message = render_to_string('emails/thankyou_email_body.txt',context)

    # don't send email if we are doing load testing or random user generation for some reason
    if not (settings.FEATURES.get('AUTOMATIC_AUTH_FOR_TESTING')):
        from_address = MicrositeConfiguration.get_microsite_configuration_value(
            'email_from_address',
            settings.DEFAULT_FROM_EMAIL
        )
        try:
            if settings.FEATURES.get('REROUTE_ACTIVATION_EMAIL'):
                dest_addr = settings.FEATURES['REROUTE_ACTIVATION_EMAIL']
                message = ("Thank you for mail %s (%s):\n" % (head_user_object, head_user_object.email) +
                           '-' * 80 + '\n\n' + message)
                send_mail(subject, message, from_address, [dest_addr], fail_silently=False)
            else:
                _res = head_user_object.email_user(subject, message, from_address)
                _res1 = rcc_user_object.email_user(subject, message, from_address)
                
        except:
            log.warning('Unable to send thank you email to user', exc_info=True)
            js['value'] = _('Could not send thank you e-mail.')
            # What is the correct status code to use here? I think it's 500, because
            # the problem is on the server's end -- but also, the account was created.
            # Seems like the core part of the request was successful.
            return JsonResponse(js, status=500)     

    return JsonResponse({'success': True,})
Exemple #6
0
def _get_or_create_oauth_user(strategy,
                              detail,
                              request=None,
                              mobile_client=False,
                              created_on='web'):
    '''
    strategy -- strategy obj
    detail -- oauth登录拿到token时的response
    '''
    backend = strategy.backend
    _created = False
    uid = get_uid(strategy, detail)
    # weibo新接口uid改名叫做id
    if not uid:
        uid = detail.get('id')
    # weixin
    if backend.name in ('weixin', 'weixinapp'):
        weixin_unionid = detail.get('unionid')
        if weixin_unionid:
            weixin_users = UserSocialAuth.objects.filter(
                weixin_unionid=weixin_unionid).order_by('id')
            weixin_users_count = weixin_users.count()
            # 微信只有一个UserSocialAuth时,使用这个
            if weixin_users_count == 1:
                user = weixin_users[0].user
                user.backend = "%s.%s" % (backend.__module__,
                                          backend.__class__.__name__)
                return (user, False)
            elif weixin_users_count > 1:
                # 有web则永远返回第一个web用户
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith('web'):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__,
                                                  backend.__class__.__name__)
                        return (user, False)
                # 否则返回mobile用户
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith(
                            'mobile'):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__,
                                                  backend.__class__.__name__)
                        return (user, False)
                # 否则返回weixin app用户(微信服务号活动生成)
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith('app'):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__,
                                                  backend.__class__.__name__)
                        return (user, False)
                # 没有第四种逻辑, 但是还是加上吧
                user = weixin_users[0].user
                user.backend = "%s.%s" % (backend.__module__,
                                          backend.__class__.__name__)
                return (user, False)
    if backend.name == 'chinamobile':
        extra_data = backend.extra_data(None, uid, detail, {})
        phone_number = extra_data.get('phone_number', None)
        try:
            user_profile = UserProfile.objects.get(phone_number=phone_number)
            user = user_profile.user
            user.backend = "%s.%s" % (backend.__module__,
                                      backend.__class__.__name__)
            return (user, False)
        except:
            pass
    result = social_user(strategy, uid)
    # 已有账户,直接登录
    if result['user']:
        user = result['user']
    # 否则创建用户,之后登录
    else:
        user = User()
        user.username = str(uuid.uuid4()).replace('-', '')[:20]
        user.email = None
        # oauth的自动激活
        user.is_active = True
        user.set_unusable_password()
        user.save()
        extra_data = backend.extra_data(user, uid, detail, {})
        profile = UserProfile(user=user)
        nickname = get_validate_nickname(extra_data['username'])
        oauth_nickname = nickname
        # 重名加后缀,最多尝试10次
        MAX_TRY_TIMES = 10
        while MAX_TRY_TIMES:
            try:
                UserProfile.objects.get(nickname=nickname)
                suffix = str(uuid.uuid4().int)[:6]
                nickname = '{}{}'.format(oauth_nickname, suffix)
                MAX_TRY_TIMES = MAX_TRY_TIMES - 1
            except UserProfile.DoesNotExist:
                break
        profile.phone_number = extra_data.get('phone_number', None)
        profile.nickname = nickname
        profile.unique_code = profile.get_unique_code()
        if request:
            profile.set_register_extra(request=request,
                                       cover_data={'channel': backend.name})
        if extra_data.get('profile_image_url'):
            profile.avatar = extra_data['profile_image_url']
        if extra_data.get('gender'):
            profile.gender = extra_data['gender']
        if extra_data.get('year_of_birth'):
            profile.year_of_birth = extra_data['year_of_birth']
        if backend.name == 'chinamobile':
            profile.register_type = 'migu'
            profile.register_auto = 1
        profile.save()
        # TODO: AuthAlreadyAssociated
        # 此oauth账号之前已经绑定了学堂在线的账号
        new_associate_user(strategy, uid, user, detail, created_on=created_on)
        _created = True
        # Track this user register event in oauth
        if not mobile_client:  # do not track api client log 2015.5.26
            event_type = 'weixinapp.user.register_success' if created_on == 'weixinapp' else 'oauth.user.register_success'
            track_log(request, event_type, {
                'success': True,
                'uid': user.id,
                'provider': backend.name,
            })
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    return (user, _created)