Пример #1
0
def _log_and_raise_inactive_user_auth_error(unauthenticated_user):
    """
    Depending on Django version we can get here a couple of ways, but this takes care of logging an auth attempt
    by an inactive user, re-sending the activation email, and raising an error with the correct message.
    """
    if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
        AUDIT_LOG.warning(
            u"Login failed - Account not active for user.id: {0}, resending activation"
            .format(unauthenticated_user.id))
    else:
        AUDIT_LOG.warning(
            u"Login failed - Account not active for user {0}, resending activation"
            .format(unauthenticated_user.username))

    profile = UserProfile.objects.get(user=unauthenticated_user)
    compose_and_send_activation_email(unauthenticated_user, profile)

    raise AuthFailedError(
        error_code='inactive-user',
        context={
            'platformName':
            configuration_helpers.get_value('PLATFORM_NAME',
                                            settings.PLATFORM_NAME),
            'supportLink':
            configuration_helpers.get_value('SUPPORT_SITE_LINK',
                                            settings.SUPPORT_SITE_LINK)
        })
Пример #2
0
def inactive_user_view(request):
    """
    A newly or recently registered user has completed the social auth pipeline.
    Their account is not yet activated, but we let them login since the third party auth
    provider is trusted to vouch for them. See details in pipeline.py.

    The reason this view exists is that if we don't define this as the
    SOCIAL_AUTH_INACTIVE_USER_URL, inactive users will get sent to LOGIN_ERROR_URL, which we
    don't want.

    If the third_party_provider.skip_email_verification is set then the user is activated
    and verification email is not sent
    """
    # 'next' may be set to '/account/finish_auth/.../' if this user needs to be auto-enrolled
    # in a course. Otherwise, just redirect them to the dashboard, which displays a message
    # about activating their account.
    user = request.user
    profile = UserProfile.objects.get(user=user)
    activated = user.is_active
    # If the user is registering via 3rd party auth, track which provider they use
    if third_party_auth.is_enabled() and pipeline.running(request):
        running_pipeline = pipeline.get(request)
        third_party_provider = provider.Registry.get_from_pipeline(
            running_pipeline)
        if third_party_provider.skip_email_verification and not activated:
            user.is_active = True
            user.save()
            activated = True
    if not activated:
        compose_and_send_activation_email(user, profile)

    return redirect(request.GET.get('next', 'dashboard'))
Пример #3
0
 def handle_failed_authentication(self, user):
     compose_and_send_activation_email(user,user.profile)
     #send_reactivation_email_for_user(user)
     return JsonResponse({
         "status": 400,
         "message": "In order to sign in, you need to activate your account. We just sent an activation link to {}.".format(user.email),
     })
Пример #4
0
def _log_and_raise_inactive_user_auth_error(unauthenticated_user):
    """
    Depending on Django version we can get here a couple of ways, but this takes care of logging an auth attempt
    by an inactive user, re-sending the activation email, and raising an error with the correct message.
    """
    if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
        AUDIT_LOG.warning(
            u"Login failed - Account not active for user.id: {0}, resending activation"
            .format(unauthenticated_user.id))
    else:
        AUDIT_LOG.warning(
            u"Login failed - Account not active for user {0}, resending activation"
            .format(unauthenticated_user.username))

    profile = UserProfile.objects.get(user=unauthenticated_user)
    compose_and_send_activation_email(unauthenticated_user, profile)

    raise AuthFailedError(error_code='inactive-user')
Пример #5
0
    def post(self, request, **kwargs):  # lint-amnesty, pylint: disable=unused-argument
        """
        Returns status code.

        Arguments:
            request (HttpRequest): The request, used to get the user
        """
        try:
            user = request.user
            if not user.is_active:
                compose_and_send_activation_email(user, user.profile)
            return Response(
                status=status.HTTP_200_OK
            )
        except Exception:  # pylint: disable=broad-except
            return Response(
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
Пример #6
0
def send_account_activation_email(user, profile, registration=None):
    """
    Send adg account activation emails.

    Args:
        user (User): User to which email will be sent.
        profile (UserProfile): Profile of the user.
        registration (Registration): Registration of the user.

    Returns:
        None
    """
    from common.djangoapps.student.views import compose_and_send_activation_email
    from common.djangoapps.student.models import Registration

    if is_testing_environment():
        compose_and_send_activation_email(user, profile, registration)
        return

    if registration is None:
        registration = Registration.objects.get(user=user)

    compose_and_send_adg_activation_email(user, registration.activation_key)
Пример #7
0
    def post(self, request, **kwargs):
        #logs.info('request-->%s', request.__dict__)
        popular_topic_list = []
        data = request.data
        if 'HTTP_KEY' and 'HTTP_SECRET' in request.data:
            popular_topic_list = []
            #logs.info('key and secret parameter in header')
            key = data.get('HTTP_KEY')
            secret = data.get('HTTP_SECRET')
            #logs.info('key, secret %s,%s',key,secret)
            #from provider.oauth2.models import Client
            from oauth2_provider.models import Application
            cliet_obj = Application.objects.filter(client_id=key,
                                                   client_secret=secret)
            if not cliet_obj:
                popular_topic_dict = {}
                popular_topic_dict["result"] = "Invalid Key and Secret"
                popular_topic_list.append(popular_topic_dict)
                return JsonResponse(popular_topic_list, status=200, safe=False)
        else:
            popular_topic_dict = {}
            popular_topic_dict["result"] = "Invalid Key and Secret"
            popular_topic_list.append(popular_topic_dict)
            return JsonResponse(popular_topic_list, status=200, safe=False)
        generated_password = generate_password()
        if 'emailid' in request.data:
            email = data.get("emailid", "")
            name = data.get('name', "")
            user_present = User.objects.filter(email=email)
            if user_present:
                user_present = user_present[0]
                mandatory_fields = [
                    "username", "emailid", "password", "name", "phone",
                    "user_type", "specialization", "hcspecialization",
                    "pincode", "country", "state", "city",
                    "csrfmiddlewaretoken"
                ]
                extradata = {}

                vfields = request.data
                for key in vfields:
                    if key not in mandatory_fields:
                        extradata[key] = vfields[key]

                update_userprofile = UserProfile.objects.filter(
                    user=user_present).update(name=name)
                user_data = extrafields.objects.get(user=user_present)
                if len(user_data.user_extra_data) > 0:
                    if '{' in user_data.user_extra_data:
                        logs.info('before -----> %s',
                                  user_data.user_extra_data)

                        data = user_data.user_extra_data.replace("\'", "\"")
                        logs.info('before1 -----> %s', data)

                        already_extradata = json.loads(data)
                        logs.info('before2 -----> %s', already_extradata)

                        all_extra_data = already_extradata.update(extradata)
                        logs.info('before3 -----> %s', already_extradata)

                        update_user_extradata = extrafields.objects.filter(
                            user_id=user_present).update(
                                user_extra_data=already_extradata)
                else:
                    update_user_extradata = extrafields.objects.filter(
                        user_id=user_present).update(user_extra_data=extradata)

                return Response(data={
                    'status': 200,
                    'sucess': 1,
                    'message': 'Registration successfully'
                },
                                status=200)

            else:
                if request.method == 'POST':
                    mandatory_fields = [
                        "username", "emailid", "password", "name", "phone",
                        "user_type", "specialization", "hcspecialization",
                        "pincode", "country", "state", "city",
                        "csrfmiddlewaretoken"
                    ]
                    extradata = {}

                    vfields = request.data
                    for key in vfields:
                        if key not in mandatory_fields:
                            extradata[key] = vfields[key]

                    email = data.get("emailid", "")
                    password = '******'
                    name = data.get('name', "")
                    phone = data.get('phone', "")
                    user_type = "dr"
                    pincode = data.get('pincode', "")
                    country = data.get('country', "")
                    state = data.get('state', "")
                    city = data.get('city', "")
                    is_active = True

                    username = email.split('@')
                    uname = username[0]
                    uname = uname.replace('.', '-')
                    try:
                        username_validation = User.objects.get(username=uname)
                        if username_validation:
                            date = datetime.datetime.now()
                            curr_time = date.strftime('%f')
                            username = uname + '_' + curr_time
                    except ObjectDoesNotExist:
                        username = uname
                    #logs.info(u'username--> %s', username)
                    form = AccountCreationForm(data={
                        'username': username,
                        'email': email,
                        'password': password,
                        'name': name,
                    },
                                               tos_required=False)

                    restricted = settings.FEATURES.get(
                        'RESTRICT_AUTOMATIC_AUTH', True)
                    try:
                        user, profile, reg = do_create_account(form)
                        logs.info(u'user-----> %s,%s', user, profile)
                    except (AccountValidationError, ValidationError):
                        # if restricted:
                        #     return HttpResponseForbidden(_('Account modification not allowed.'))
                        # Attempt to retrieve the existing user.
                        #     user = User.objects.get(username=username)
                        #     user.email = email
                        #     user.set_password(password)
                        #     user.is_active = is_active
                        #     user.save()
                        #     profile = UserProfile.objects.get(user=user)
                        #     reg = Registration.objects.get(user=user)
                        # except PermissionDenied:
                        registration_log = third_party_user_registration_log(
                            email=email,
                            status=
                            'Account creation not allowed either the user is already registered or email-id not valid',
                            data=request.data)
                        registration_log.save()

                    # if is_active:
                    #     reg.activate()
                    #     reg.save()

                    # ensure parental consent threshold is met
                    year = datetime.date.today().year
                    age_limit = settings.PARENTAL_CONSENT_AGE_LIMIT
                    profile.year_of_birth = (year - age_limit) - 1
                    profile.save()
                    user_extrainfo = extrafields(phone=phone,
                                                 rcountry=country,
                                                 rstate=state,
                                                 rcity=city,
                                                 rpincode=pincode,
                                                 user_type=user_type,
                                                 user=user,
                                                 user_extra_data=extradata)
                    user_extrainfo.save()
                    #logs.info('extrainfo --> %s',user_extrainfo)
                    create_comments_service_user(user)

                    create_or_set_user_attribute_created_on_site(
                        user, request.site)
                    user_signup_source = UserSignupSource(
                        user=user, site='vkonnecthealth.koa.docmode.org')
                    user_signup_source.save()
                    registration_log = third_party_user_registration_log(
                        email=email, status='succesful', data=request.data)
                    registration_log.save()
                    home_ongoing_course_list = []
                    home_ongoing_course_dict = {}
                    home_ongoing_course_dict['response'] = "Success"
                    logs.info(u'user--> %s,%s,%s', user, profile, reg)
                    compose_and_send_activation_email(user, profile, reg)
                    return Response(data={
                        'status': 200,
                        'sucess': 1,
                        'message': 'Registration successfully'
                    },
                                    status=200)

                    #return HttpResponse('Registration successfully')
                else:
                    home_ongoing_course_list = []
                    home_ongoing_course_dict = {}
                    home_ongoing_course_dict['response'] = "Failed"
                    registration_log = third_party_user_registration_log(
                        email=email, status='failed', data=request.POST.dict())
                    registration_logs.save()
                    return Response(data={
                        'status': 400,
                        'message': 'Registration failed'
                    },
                                    status=200)
        else:
            return Response(data={
                'status': 400,
                'message': 'Email id is not present'
            },
                            status=200)
Пример #8
0
def create_account_with_params(request, params):
    """
    Given a request and a dict of parameters (which may or may not have come
    from the request), create an account for the requesting user, including
    creating a comments service user object and sending an activation email.
    This also takes external/third-party auth into account, updates that as
    necessary, and authenticates the user for the request's session.

    Does not return anything.

    Raises AccountValidationError if an account with the username or email
    specified by params already exists, or ValidationError if any of the given
    parameters is invalid for any other reason.

    Issues with this code:
    * It is non-transactional except where explicitly wrapped in atomic to
      alleviate deadlocks and improve performance. This means failures at
      different places in registration can leave users in inconsistent
      states.
    * Third-party auth passwords are not verified. There is a comment that
      they are unused, but it would be helpful to have a sanity check that
      they are sane.
    * The user-facing text is rather unfriendly (e.g. "Username must be a
      minimum of two characters long" rather than "Please use a username of
      at least two characters").
    * Duplicate email raises a ValidationError (rather than the expected
      AccountValidationError). Duplicate username returns an inconsistent
      user message (i.e. "An account with the Public Username '{username}'
      already exists." rather than "It looks like {username} belongs to an
      existing account. Try again with a different username.") The two checks
      occur at different places in the code; as a result, registering with
      both a duplicate username and email raises only a ValidationError for
      email only.
    """
    # Copy params so we can modify it; we can't just do dict(params) because if
    # params is request.POST, that results in a dict containing lists of values
    params = dict(list(params.items()))

    # allow to define custom set of required/optional/hidden fields via configuration
    extra_fields = configuration_helpers.get_value(
        'REGISTRATION_EXTRA_FIELDS',
        getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {})
    )
    if is_registration_api_v1(request):
        if 'confirm_email' in extra_fields:
            del extra_fields['confirm_email']

    # registration via third party (Google, Facebook) using mobile application
    # doesn't use social auth pipeline (no redirect uri(s) etc involved).
    # In this case all related info (required for account linking)
    # is sent in params.
    # `third_party_auth_credentials_in_api` essentially means 'request
    # is made from mobile application'
    third_party_auth_credentials_in_api = 'provider' in params
    is_third_party_auth_enabled = third_party_auth.is_enabled()

    if is_third_party_auth_enabled and (pipeline.running(request) or third_party_auth_credentials_in_api):
        params["password"] = generate_password()

    # in case user is registering via third party (Google, Facebook) and pipeline has expired, show appropriate
    # error message
    if is_third_party_auth_enabled and ('social_auth_provider' in params and not pipeline.running(request)):
        raise ValidationError(
            {
                'session_expired': [
                    _("Registration using {provider} has timed out.").format(
                        provider=params.get('social_auth_provider'))
                ],
                'error_code': 'tpa-session-expired',
            }
        )

    if is_third_party_auth_enabled:
        set_custom_attribute('register_user_tpa', pipeline.running(request))
    extended_profile_fields = configuration_helpers.get_value('extended_profile_fields', [])
    # Can't have terms of service for certain SHIB users, like at Stanford
    registration_fields = getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {})
    tos_required = (
        registration_fields.get('terms_of_service') != 'hidden' or
        registration_fields.get('honor_code') != 'hidden'
    )

    form = AccountCreationForm(
        data=params,
        extra_fields=extra_fields,
        extended_profile_fields=extended_profile_fields,
        do_third_party_auth=False,
        tos_required=tos_required,
    )
    custom_form = get_registration_extension_form(data=params)

    # Perform operations within a transaction that are critical to account creation
    with outer_atomic():
        # first, create the account
        (user, profile, registration) = do_create_account(form, custom_form)

        third_party_provider, running_pipeline = _link_user_to_third_party_provider(
            is_third_party_auth_enabled, third_party_auth_credentials_in_api, user, request, params,
        )

        new_user = authenticate_new_user(request, user.username, form.cleaned_data['password'])
        django_login(request, new_user)
        request.session.set_expiry(0)

    # Sites using multiple languages need to record the language used during registration.
    # If not, compose_and_send_activation_email will be sent in site's default language only.
    create_or_set_user_attribute_created_on_site(user, request.site)

    # Only add a default user preference if user does not already has one.
    if not preferences_api.has_user_preference(user, LANGUAGE_KEY):
        preferences_api.set_user_preference(user, LANGUAGE_KEY, get_language())

    # Check if system is configured to skip activation email for the current user.
    skip_email = _skip_activation_email(
        user, running_pipeline, third_party_provider,
    )

    if skip_email:
        registration.activate()
    else:
        redirect_to, root_url = get_next_url_for_login_page(request, include_host=True)
        redirect_url = get_redirect_url_with_host(root_url, redirect_to)
        compose_and_send_activation_email(user, profile, registration, redirect_url)

    if settings.FEATURES.get('ENABLE_DISCUSSION_EMAIL_DIGEST'):
        try:
            enable_notifications(user)
        except Exception:  # pylint: disable=broad-except
            log.exception(f"Enable discussion notifications failed for user {user.id}.")

    _track_user_registration(user, profile, params, third_party_provider, registration)

    # Announce registration
    REGISTER_USER.send(sender=None, user=user, registration=registration)

    STUDENT_REGISTRATION_COMPLETED.send_event(
        user=UserData(
            pii=UserPersonalData(
                username=user.username,
                email=user.email,
                name=user.profile.name,
            ),
            id=user.id,
            is_active=user.is_active,
        ),
    )

    create_comments_service_user(user)

    try:
        _record_registration_attributions(request, new_user)
        _record_marketing_emails_opt_in_attribute(params.get('marketing_emails_opt_in'), new_user)
    # Don't prevent a user from registering due to attribution errors.
    except Exception:   # pylint: disable=broad-except
        log.exception('Error while attributing cookies to user registration.')

    # TODO: there is no error checking here to see that the user actually logged in successfully,
    # and is not yet an active user.
    is_new_user(request, new_user)
    return new_user
Пример #9
0
    def post(self, request, **kwargs):
        #from user_authn.views.login import _check_excessive_login_attempts
        from student.models import LoginFailures
        #from openedx.core.djangoapps.user_authn.views.login import _check_excessive_login_attempts
        self.data = request.POST.dict()
        if not ('uservalue' and 'sendotptype' and 'password' in self.data):
            return JsonResponse({
                "status": 400,
                "message": "Please enter Valid Mobile Number or Email Address or password",
            })
        if self.data.get('sendotptype') == "mobile":
            mobile = self.data.get('uservalue')
            user = User.objects.get(extrafields__phone=mobile)
            email = user.email
        else:
            email = self.data.get('uservalue')

        password = self.data.get('password')
        if not password:
            return JsonResponse({
                "status": 400,
                "message": "Password fiels can not be blank",
            })
        try:
            user = User.objects.get(email=email)
            if not user.is_active:
                registration = Registration.objects.get(user=user)
                profile = UserProfile.objects.get(user=user)
                compose_and_send_activation_email(user, profile, registration)
                return JsonResponse({
                    "status": 400,
                    "message": "Please check mail and active it.",
               })
            try:
                if user and LoginFailures.is_feature_enabled():
                    if LoginFailures.is_user_locked_out(user):
                        raise AuthFailedError(_('This account has been temporarily locked due '
                                    'to excessive login failures. Try again later.'))
                #_check_excessive_login_attempts(user)
            except Exception as e:
                logs.info(e.message)
                return JsonResponse(status=200, data={
                    "status": 400,
                    "message": "Login attempt failed",
            })

            new_user = authenticate_new_user(request, user.username, password)
            #compose_and_send_activation_email(user, profile)
            #compose_and_send_activation_email(user, profile, registration)
            django_login(request, new_user)
            request.session.set_expiry(604800 * 4)
            if not new_user.extrafields.rpincode:
                response =  JsonResponse(status=200, data={
                    "status":200,
                    "message": "profile",
                    "userid":new_user.id,
                    "number":new_user.extrafields.rcountry_code
                 })
            else:
                response = JsonResponse(status=200, data={
                    "status": 200,
                    "message": "success",
            })
            devlog = set_logged_in_cookies(request, response, new_user)
            return devlog

        except Exception as e:
            logs.info(e.message)
            return JsonResponse(status=200, data={
                    "status": 400,
                    "message": "Enter Valid password",
            })