Created
December 31, 2017 07:54
-
-
Save devxpy/e6b9bf55d6e2f310fc4f4bf9be7a8759 to your computer and use it in GitHub Desktop.
Django create user view that dynamically selects the authentication method, based on a groupdomain object thats one-to-one with the Group and profile which is one-to-one with the User
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_user(request): | |
redirect_to = request.POST.get(REDIRECT_FIELD_NAME, | |
request.GET.get(REDIRECT_FIELD_NAME, urlresolvers.reverse(user_panel))) | |
group = get_object_or_404(GroupDomain, domain=request.META['HTTP_HOST']).group | |
verification_methods = group.groupdomain.verification_method | |
ctx_forms = {'grade': forms.GradeForm} | |
# Get the appropriate forms based on the domain settings | |
if GroupDomain.USERNAME in verification_methods: | |
ctx_forms['create_user'] = UserCreationForm | |
if GroupDomain.EMAIL in verification_methods: | |
if ctx_forms['create_user']: | |
ctx_forms['email'] = forms.CreateUserWithEmailForm | |
else: | |
ctx_forms['create_user'] = forms.CreateUserWithEmailForm | |
if GroupDomain.PHONE in verification_methods: | |
if ctx_forms['create_user']: | |
ctx_forms['phone'] = forms.CreateUserWithPhoneForm | |
else: | |
ctx_forms['create_user'] = forms.CreateUserWithPhoneForm | |
if request.method == 'POST': | |
form = ctx_forms['create_user'](request.POST) | |
if form.is_valid(): | |
user = form.save() | |
user.refresh_from_db() # load the profile instance created by the signal | |
group.user_set.add(user) # Add him to proper group | |
raw_password = form.cleaned_data.get('password1') | |
form = ctx_forms.get('grade')(request.POST) | |
if form and form.is_valid(): | |
user.profile.grade = form.cleaned_data.get('grade') | |
form = ctx_forms.get('email')(request.POST) | |
if form and form.is_valid(): | |
user.email = form.cleaned_data.get('email') | |
form = ctx_forms.get('phone_number')(request.POST) | |
if form and form.is_valid(): | |
user.profile.phone_number = form.cleaned_data.get('phone_number') | |
# Ensure the user-originating redirection url is safe. | |
if not is_safe_url(url=redirect_to, host=request.get_host()): | |
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) | |
# All checks complete, save the user and log him in. Redirect to appropriate page | |
user.save() | |
user = authenticate(username=user.username, password=raw_password) | |
auth_login(request, user) | |
return HttpResponseRedirect(redirect_to) | |
else: | |
# Init all forms | |
for form_type, form in ctx_forms.items(): | |
ctx_forms['form_type'] = form() | |
return render(request, "login_flows/create_account.html", {'forms': ctx_forms, 'next_page': redirect_to}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment