Giter Site home page Giter Site logo

Comments (15)

jpadilla avatar jpadilla commented on July 28, 2024

The way it currently works is we use your User's model USERNAME_FIELD. If you just want to use another field for authentication you can implement your own class of JSONWebTokenSerializer like:

class CustomJWTSerializer(JSONWebTokenSerializer):
    username_field = 'email'

from django-rest-framework-jwt.

syedsaqibali avatar syedsaqibali commented on July 28, 2024

Could this information be adde to the Readme?

Alternatively, (and I think it is cleaner), can there be another API for
getting a token based on username/email address without the user specifying
which one it is?

On Sep 17, 2014 10:02 AM, "José Padilla" [email protected] wrote:

The way it currently works is we use your User's model USERNAME_FIELD. If
you just want to use another field for authentication you can implement
your own class of JSONWebTokenSerializer like:

class CustomJWTSerializer(JSONWebTokenSerializer):
username_field = 'email'

Reply to this email directly or view it on GitHub
#34 (comment)
.

from django-rest-framework-jwt.

jpadilla avatar jpadilla commented on July 28, 2024

@syedsaqibali I think it's time to have some more formal docs. So i'll have this in mind.

Do you have any suggestions on how this should be?

from django-rest-framework-jwt.

Nadrieril avatar Nadrieril commented on July 28, 2024

I don't think you should use a serializer at all. We can't know which fields are needed for a given (custom?) backend unless we hard-code them. I suggest you could directly do authenticate(**request.DATA), so that any credentials combination can work

from django-rest-framework-jwt.

aganhuyag avatar aganhuyag commented on July 28, 2024

@jpadilla Do I have to fork the whole app and use my own implementation if I wanted email authentication? Or is there a way to just use my own class with the default code?

from django-rest-framework-jwt.

jpadilla avatar jpadilla commented on July 28, 2024

@aganhuyag you should be able to implement your own custom view extending from ObtainJSONWebToken that uses your own serializer. You could also try something like I mentioned in #34 (comment).

I haven't tried this myself, so if anyone wants to share their solution that'd be great.

from django-rest-framework-jwt.

stunaz avatar stunaz commented on July 28, 2024

👍 for getting a token based on username/email address without the user specifying
which one it is, or if we can specify in the config which field to use or both

from django-rest-framework-jwt.

jpadilla avatar jpadilla commented on July 28, 2024

I'd be happy to check out pull requests for this. Currently not a pressing issue for me. If anyone wants to tackle it, go right ahead. I'll help out however I can.

from django-rest-framework-jwt.

hoIIer avatar hoIIer commented on July 28, 2024

@syedsaqibali @aganhuyag I use email/password for authentication and I haven't needed to do anything special. As @jpadilla mentioned above, the django documentation states that you use the USERNAME_FIELD on a subclass of AbstractUser to specify your own identifier field.. Set that to 'email' and thats all you should need to do

from django-rest-framework-jwt.

syedsaqibali avatar syedsaqibali commented on July 28, 2024

Well, my workaround is to have the user enter data into a field named username_or_email. Then I check that entry to see if it contains a "@". If it does, then I look that email address up in the User table and get the username. Otherwise, I take what they gave me as the username. Then I login with the (possibly derived) username and password.

from django-rest-framework-jwt.

hoIIer avatar hoIIer commented on July 28, 2024

@syedsaqibali interesting.. which version of django do you use? are you allowing users to use either email OR a custom username? in my current app Im building I actually use email as the identifier but I also automatically generate a unique username based on their first + last name so you can do pretty url's eg. myapp.com/people/barrackobama

from django-rest-framework-jwt.

syedsaqibali avatar syedsaqibali commented on July 28, 2024

@ericonkanen Django version 1.7.1

Yes. I am allowing my users to login with their email OR their username. I think its more elegant that way.

I also have the same requirements in my app as you to make the URL pretty and readable. However. I wouldn't advise at all the way you are doing it. If their name has special or non-English characters, you will run into all kinds of problem. What I did instead was to create a new model called "Profile" which looks like this:


from autoslug import AutoSlugField
class Profile(models.Model):
    user = models.OneToOneField(User)
    slug = AutoSlugField(
        populate_from='username',
        always_update=True,
        unique=True,
    )

To get the AutoSlugField package I did:


$ pip install django-autoslug-field

Now, to make my URLs pretty, I use Profile.slug. It's guaranteed to be a reasonable length and safe to use in a URL. Try it! Also, using my own Profile class instead of Django's User model allows me to more easily add custom fields to this model.

from django-rest-framework-jwt.

hoIIer avatar hoIIer commented on July 28, 2024

@syedsaqibali interesting, I'll check that out!.. I do have some filters on it, e.g. first and last names can only be alphanumeric (letters/numbers), and if there is a name collision, it appends a number to the end... e.g. /people/bobsmith.39 (got that idea from graph.facebook.com/)

from django-rest-framework-jwt.

jpadilla avatar jpadilla commented on July 28, 2024

Closing this for lack of activity. Will reopen if there are concrete actions for a next step.

from django-rest-framework-jwt.

elflamo avatar elflamo commented on July 28, 2024

@jpadilla As per your suggestion of making a Customize Serializer, i've implemented the same as below which works absolutely fine:

This works for 'username_or_email' and 'password' fields where the user can enter its username or email and get the JSONWebToken for correct credentials.

class CustomJWTSerializer(JSONWebTokenSerializer):
username_field = 'username_or_email'

def validate(self, attrs):

    password = attrs.get("password")
    user_obj = User.objects.filter(email=attrs.get("username_or_email")).first() or User.objects.filter(username=attrs.get("username_or_email")).first()
        if user_obj is not None:
            credentials = {
                'username':user_obj.username,
                'password': password
            }
            if all(credentials.values()):
                user = authenticate(**credentials)
                if user:
                    if not user.is_active:
                        msg = _('User account is disabled.')
                        raise serializers.ValidationError(msg)

                    payload = jwt_payload_handler(user)

                    return {
                        'token': jwt_encode_handler(payload),
                        'user': user
                    }
                else:
                    msg = _('Unable to log in with provided credentials.')
                    raise serializers.ValidationError(msg)

            else:
                msg = _('Must include "{username_field}" and "password".')
                msg = msg.format(username_field=self.username_field)
                raise serializers.ValidationError(msg)

        else:
            msg = _('Account with this username or email does not exists')
            raise serializers.ValidationError(msg)

    return super(CustomJWTSerializer, self).validate(attrs)

from django-rest-framework-jwt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.