简体   繁体   中英

Custom authenticate method or maybe some other way to do the same? Django

this is a begginers question. I have a database in mysql with tables to store users with a username and a password, simple as that. I dont want to use the authentications backends and tables that django installs the first time you run 'SyncDb'. So my question is: how do i tell django to use the database that i created instead of looking for active Users in the pre defined databases. I´m using this code but of course this is looking for users in the already mention 'auth_user' table.

class LoginView(FormView):
    form_class = LoginForm
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'login.html'
    success_url = 'index'

    def form_valid(self, form):
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        user = authenticate(username=username, 
                            password=password)
        if user is not None:
            if user.is_active:
                login(self.request, user)
                return HttpResponseRedirect(self.get_success_url())
        else:        
            return self.form_invalid(form)

    def form_invalid(self):
        return HttpResponseRedirect(reverse('app_name:login'))

    def get_success_url(self):
        if self.success_url:
            redirect_to = self.success_url
        else:
            redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')

        netloc = urlparse.urlparse(redirect_to)[1]
        if not redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL
        elif netloc and netloc != self.request.get_host():
            redirect_to = settings.LOGIN_REDIRECT_URL
        return redirect_to

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        if form.is_valid():
            return self.form_valid(form)
        else:                
            return self.form_invalid()

So that´s my begginers question. Thank you very much

PS: my form_invalid() is not working...(error: passing 2 parameters instead of 1) any suggestions please tell me. Again, thank you very much

We had to figure this out for our project and the initial confusion comes from the fact that you basically need to handle two issues in Django to make this happen:

1) Make sure that that app is routed to the correct database 1a) Make sure that other database can actually be written by Django

2) Create an "app" module to use to overwrite the default user model

Luckily this is pretty much straightforward once the problem is clearly defined.

https://docs.djangoproject.com/en/dev/topics/db/multi-db/

The first section "Defining your databases" will show you how to add additional databases to your project. Make sure you have credentials for Django to use to access, so depending on your access structure, that may include an additional step or not.

After that the section "Automatic database routing" will explain the general idea behind db routers. However, I recommend you check out this excellent discussion and leverage that code to make your database routing easier: http://justcramer.com/2010/12/30/database-routers-in-django/ . This way you can just make your project use this router and define a lib in your settings.py (DATABASE_CONFIG) to tell each application where to route after setting DATABASE_ROUTERS to the code at the link. Make your default router the one with all the django stuff, then define your legacy db whenever necessary.

Lastly, for the user model check out the docs on "Customizing authentication in Django" (I can't post the link because this is my first answer and I do not have enough reputation). You will need to write a custom model (and potentially admin forms and custom authentication for permissions based on your implementation) and include it through your project settings.py with AUTH_USER_MODEL. The key section on that page is "Substituting a custom User model". If it is as simple as just matching a password to a user it should be mostly painless, however, be careful how your passwords are hashed. PASSWORD_HASHERS in your settings.py tells django the hashers to use on passwords when saving them (and the preferred order). If you want to keep a certain hashing scheme you need to move that to the top of the list, otherwise, Django will port it to the first listed and thus preferred scheme when it needs to do a PW access. This is actually a great feature as it will auto-migrate passwords to stronger schemes, but may be something to be mindful of if you need to integrate with other systems.

As a general pointer (and this is in no way intended as a RTM) the Django documents are very good and will typically answer your questions (and if not the source is quite readable and I've had to solve a few things that way). However, as you might notice, until you realize the issue you are trying to fix, and what Django calls it, it can be a little confusing to fit the pieces together. It will be worth your time if you plan to do anything at all with Django to get a good read of the primary documentation, possibly twice, to help make the pieces fit. Hopefully this answers your question and gives you a sense of where to go, as you can see this scenario can get a little broad so let me know if a more specific question gives you issues, otherwise these are the key points I recall implementing and during a code review as I wrote this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM