def check_edxapp_account_conflicts(email, username): """ Get an executes the check_account_exists for tests """ try: from openedx.core.djangoapps.user_api.accounts.api import check_account_exists except ImportError: def check_account_exists(email=None, username=None): """ Fake definition for check_account_exists edxapp function """ return email and username return check_account_exists(email=email, username=username)
def _handle_duplicate_email_username(self, data): # TODO Verify whether this check is needed here - it may be duplicated in user_api. email = data.get('email') username = data.get('username') conflicts = check_account_exists(email=email, username=username) if conflicts: conflict_messages = { "email": accounts_settings.EMAIL_CONFLICT_MSG.format(email_address=email), # pylint: disable=no-member "username": accounts_settings.USERNAME_CONFLICT_MSG.format(username=username), # pylint: disable=no-member } errors = { field: [{"user_message": conflict_messages[field]}] for field in conflicts } return self._create_response(errors, status_code=409)
def post(self, request): """Create the user's account. You must send all required form fields with the request. You can optionally send a "course_id" param to indicate in analytics events that the user registered while enrolling in a particular course. Arguments: request (HTTPRequest) Returns: HttpResponse: 200 on success HttpResponse: 400 if the request is not valid. HttpResponse: 409 if an account with the given username or email address already exists HttpResponse: 403 operation not allowed """ data = request.POST.copy() email = data.get('email') username = data.get('username') # Handle duplicate email/username conflicts = check_account_exists(email=email, username=username) if conflicts: conflict_messages = { "email": accounts.EMAIL_CONFLICT_MSG.format(email_address=email), "username": accounts.USERNAME_CONFLICT_MSG.format(username=username), } errors = { field: [{ "user_message": conflict_messages[field] }] for field in conflicts } return JsonResponse(errors, status=409) # Backwards compatibility: the student view expects both # terms of service and honor code values. Since we're combining # these into a single checkbox, the only value we may get # from the new view is "honor_code". # Longer term, we will need to make this more flexible to support # open source installations that may have separate checkboxes # for TOS, privacy policy, etc. if data.get("honor_code") and "terms_of_service" not in data: data["terms_of_service"] = data["honor_code"] try: user = create_account_with_params(request, data) except AccountValidationError as err: errors = {err.field: [{"user_message": text_type(err)}]} return JsonResponse(errors, status=409) except ValidationError as err: # Should only get non-field errors from this function assert NON_FIELD_ERRORS not in err.message_dict # Only return first error for each field errors = { field: [{ "user_message": error } for error in error_list] for field, error_list in err.message_dict.items() } return JsonResponse(errors, status=400) except PermissionDenied: return HttpResponseForbidden(_("Account creation not allowed.")) response = JsonResponse({"success": True}) set_logged_in_cookies(request, response, user) return response
def post(self, request): """Create the user's account. You must send all required form fields with the request. You can optionally send a "course_id" param to indicate in analytics events that the user registered while enrolling in a particular course. Arguments: request (HTTPRequest) Returns: HttpResponse: 200 on success HttpResponse: 400 if the request is not valid. HttpResponse: 409 if an account with the given username or email address already exists HttpResponse: 403 operation not allowed """ data = request.POST.copy() email = data.get('email') username = data.get('username') # Handle duplicate email/username conflicts = check_account_exists(email=email, username=username) if conflicts: conflict_messages = { "email": accounts.EMAIL_CONFLICT_MSG.format(email_address=email), "username": accounts.USERNAME_CONFLICT_MSG.format(username=username), } errors = { field: [{"user_message": conflict_messages[field]}] for field in conflicts } return JsonResponse(errors, status=409) # Backwards compatibility: the student view expects both # terms of service and honor code values. Since we're combining # these into a single checkbox, the only value we may get # from the new view is "honor_code". # Longer term, we will need to make this more flexible to support # open source installations that may have separate checkboxes # for TOS, privacy policy, etc. if data.get("honor_code") and "terms_of_service" not in data: data["terms_of_service"] = data["honor_code"] try: user = create_account_with_params(request, data) except AccountValidationError as err: errors = { err.field: [{"user_message": text_type(err)}] } return JsonResponse(errors, status=409) except ValidationError as err: # Should only get non-field errors from this function assert NON_FIELD_ERRORS not in err.message_dict # Only return first error for each field errors = { field: [{"user_message": error} for error in error_list] for field, error_list in err.message_dict.items() } return JsonResponse(errors, status=400) except PermissionDenied: return HttpResponseForbidden(_("Account creation not allowed.")) response = JsonResponse({"success": True}) set_logged_in_cookies(request, response, user) return response
def post(self, request): """Create the user's account. You must send all required form fields with the request. You can optionally send a "course_id" param to indicate in analytics events that the user registered while enrolling in a particular course. Arguments: request (HTTPRequest) Returns: HttpResponse: 200 on success HttpResponse: 400 if the request is not valid. HttpResponse: 409 if an account with the given username or email address already exists """ data = request.POST.copy() email = data.get('email') username = data.get('username') # Handle duplicate email/username conflicts = check_account_exists(email=email, username=username) if conflicts: conflict_messages = { "email": _( # Translators: This message is shown to users who attempt to create a new # account using an email address associated with an existing account. u"It looks like {email_address} belongs to an existing account. " u"Try again with a different email address.").format( email_address=email), "username": _( # Translators: This message is shown to users who attempt to create a new # account using a username associated with an existing account. u"The username you entered is already being used. Please enter another username." ).format(username=username), } errors = { field: [{ "user_message": conflict_messages[field] }] for field in conflicts } return JsonResponse(errors, status=409) # Backwards compatibility: the student view expects both # terms of service and honor code values. Since we're combining # these into a single checkbox, the only value we may get # from the new view is "honor_code". # Longer term, we will need to make this more flexible to support # open source installations that may have separate checkboxes # for TOS, privacy policy, etc. if data.get("honor_code") and "terms_of_service" not in data: data["terms_of_service"] = data["honor_code"] try: user = create_account_with_params_custom(request, data) except ValidationError as err: # Should only get non-field errors from this function assert NON_FIELD_ERRORS not in err.message_dict # Only return first error for each field errors = { field: [{ "user_message": error } for error in error_list] for field, error_list in err.message_dict.items() } return JsonResponse(errors, status=400) response = JsonResponse({"success": True}) set_logged_in_cookies(request, response, user) return response
def check_edxapp_account_conflicts(email, username): """ Exposed function to check conflicts """ return check_account_exists(email=email, username=username)
def create(self, request): """Creates a new user account for the site that calls this view To use, perform a token authenticated POST to the URL:: /tahoe/api/v1/registrations/ Required arguments (JSON data): "username" "email" "name" Optional arguments: "password" "send_activation_email" Returns: HttpResponse: 200 on success, {"user_id ": 9} HttpResponse: 400 if the request is not valid. HttpResponse: 409 if an account with the given username or email address already exists The code here is adapted from the LMS ``appsembler_api`` bulk registration code. See the ``appsembler/ginkgo/master`` branch """ data = request.data password_provided = 'password' in data # set the honor_code and honor_code like checked, # so we can use the already defined methods for creating an user data['honor_code'] = "True" data['terms_of_service'] = "True" if password_provided: if 'send_activation_email' in data and data[ 'send_activation_email'] == "False": data['send_activation_email'] = False else: data['send_activation_email'] = True else: data['password'] = create_password() data['send_activation_email'] = False email = request.data.get('email') username = request.data.get('username') # Handle duplicate email/username conflicts = check_account_exists(email=email, username=username) if conflicts: errors = {"user_message": "User already exists"} return Response(errors, status=409) try: user = create_account_with_params( request=request, params=data, send_activation_email_flag=data['send_activation_email']) # set the user as active if password is provided # meaning we don't have to send a password reset email user.is_active = password_provided user.save() user_id = user.id if not password_provided: success = send_password_reset_email(request) if not success: log.error('Tahoe Reg API: Error sending password reset ' 'email to user {}'.format(user.username)) except ValidationError as err: log.error('ValidationError. err={}'.format(err)) # Should only get non-field errors from this function assert NON_FIELD_ERRORS not in err.message_dict # Only return first error for each field # TODO: Let's give a clue as to which are the error causing fields errors = {"user_message": "Invalid parameters on user creation"} return Response(errors, status=400) return Response({'user_id ': user_id}, status=200)
def post(self, request): """ POST /api/tams_api/accounts email, username, name, uid """ # Only superusers can create an account if not request.user.is_superuser: return Response(status=status.HTTP_403_FORBIDDEN) data = request.POST.copy() email = data.get('email') # Handle duplicate email conflicts = check_account_exists(email=email) if conflicts: errorMsg = " and ".join(conflicts) return Response({ 'code': status.HTTP_409_CONFLICT, 'message': "{} already used for another account.".format(errorMsg) }, status=status.HTTP_409_CONFLICT) redirect_uri = '' backend_name = 'azuread-oauth2' request.social_strategy = social_utils.load_strategy(request) request.backend = social_utils.load_backend(request.social_strategy, backend_name, redirect_uri) username = get_username(strategy=request.social_strategy, details=data) data["username"] = username['username'] data["honor_code"] = True; data["terms_of_service"] = True; try: user = create_user_account(request, data) except AccountValidationError as err: return Response({ 'code': status.HTTP_400_BAD_REQUEST, 'field': [{"user_message": err.message}] }, status=status.HTTP_400_BAD_REQUEST) except ValidationError as err: errors = { 'field': [{"user_message": error} for error in error_list] for field, error_list in err.message_dict.items() } return Response(errors, status=status.HTTP_400_BAD_REQUEST) except AuthAlreadyAssociated as err: return Response({ 'code': status.HTTP_400_BAD_REQUEST, 'message': err.message }, status=status.HTTP_400_BAD_REQUEST) except TamsApiInternalError as err: return Response({ 'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'message': err.message }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) course_id = data.get('course_id') if course_id: try: username = user['username'] log.info("Enrolling course {} for user {}".format(course_id, username)) enrollment = create_user_enrollment(username, course_id) user['enrolledCourseId'] = enrollment['course_details']['course_id'] except Exception as err: log.error(err.message) return Response(user)
def post(self, request, format=None): """ """ # Gather all the request data username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') contact_name = request.POST.get('contact_name') activate = request.POST.get('activate', False) org_manager = request.POST.get('org_manager', False) send_email = request.POST.get('send_email', False) language = request.POST.get('language', 'en') conflicts = check_account_exists(email=email, username=username) if conflicts: return JsonResponse({'conflict_on_fields': conflicts}, status=409) data = { 'username': username, 'email': email, 'password': password, 'name': contact_name, } # Go ahead and create the new user with transaction.commit_on_success(): form = AccountCreationForm( data=data, tos_required=False, ) (user, profile, registration) = _do_create_account(form) create_comments_service_user(user) if send_email: with override_language(language): context = { 'name': profile.name, 'key': registration.activation_key, } # composes activation email subject = render_to_string('emails/activation_email_subject.txt', context) subject = ''.join(subject.splitlines()) message = render_to_string('emails/activation_email.txt', context) message_html = None if (settings.FEATURES.get('ENABLE_MULTIPART_EMAIL')): message_html = render_to_string('emails/html/activation_email.html', context) from_address = microsite.get_value( 'email_from_address', settings.DEFAULT_FROM_EMAIL ) try: mail.send_mail(subject, message, from_address, [user.email], html_message=message_html) except Exception: # pylint: disable=broad-except log.error(u'Unable to send activation email to remotely created user from "%s"', from_address, exc_info=True) # Assing the user to the org management roles if org_manager: # We have to make them active for the roles to stick user.is_active = True user.save() creator_role = OrgCourseCreatorRole(org_manager) creator_role.add_users(user) rerun_role = OrgRerunCreatorRole(org_manager) rerun_role.add_users(user) user.is_active = False user.save() if activate: registration.activate() return JsonResponse({"success": True}, status=201)