Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

authentication #4

Open
MohamedShawky opened this issue Apr 23, 2017 · 14 comments
Open

authentication #4

MohamedShawky opened this issue Apr 23, 2017 · 14 comments

Comments

@MohamedShawky
Copy link

i have download this project but it didnot work
please contact me

@BurkovBA
Copy link
Owner

BurkovBA commented Apr 24, 2017

@MohamedShawky
Hi, Mohamed!

So, what's the issue? What did you try to do?

This app is meant to work as follows: you go to /api/auth/ page, authenticate with your Username and Password and receive a JSON Token in response. You save it somewhere (e.g. in LocalStorage/SessionStorage or Cookie) on client side and upon each request send it to the server with Authentication header. TokenAuthentication backed on server recognises the token and assigns request.user variable to the corresponding Mongoengine User Document.

If you want to chat, here's a gitter: https://gitter.im/BurkovBA/django-rest-framework-mongoengine

@MohamedShawky
Copy link
Author

@BurkovBA
Hi, BurkovBA!
First, I would like to thank you for your cooperation
can you help me in develop an web applicaion which it like facebook
how to make it , how i devlope post,like,comment
upload image, video, file
if you can help me please tell me
i have building database ,
thank you in advance

@BurkovBA
Copy link
Owner

BurkovBA commented Apr 25, 2017

@MohamedShawky
Hi, Mohamed.

No I can't help you develop the whole application, sorry. It will take you half a year to a year (literally) to do that and I don't see any point to create yet another social network. If you have any small, specific questions on DRF-ME, I can answer them, though.

At the same time, I'm currently working on my personal blog, which has frontend written in obsolete Angular 1 and will have a backend in Django-REST-Framework-Mongoengine. You can take a look at frontend here: https://github.com/BurkovBA/BurkovBA.github.io. The backend will be available later, when I'm done with new features for DRF-ME, I've long had to implement.

If you're studying the programming to use it as a social lift, striving to create a large business and improve your financial situation and social status, let me suggest that you study the basics of business, such as how to do sales, then study the hottest emerging markets, read a lot of business literature and find a window of opportunity to create a very simple business, simplest possible. In parallel with that, I suggest that you improve in the programming basics and get a full-time job in a tech business that will allow you to both improve as a professional and get a fair amount of money for the next couple of years.

Good luck!

@MohamedShawky
Copy link
Author

MohamedShawky commented Apr 26, 2017

@BurkovBA
thanks alot
i have a help in a specific code which like that

class ReplyComment(EmbeddedDocument):
     user = ReferenceField(Users)
     content = StringField()

class Comments(EmbeddedDocument):
    user = ReferenceField(Users)
    content = StringField()
    rate = IntField()
    reply = ListField(EmbeddedDocumentField(ReplyComment))

class Projects(Document):
    likes = IntField()
    rate = IntField ()
    technologies = ListField(StringField())
    sponser = BooleanField(default = 'false')
    file = FileField()
    image = ImageField()
    video = FileField()

how i make DRF-ME to this classes
and make user interact with them
If appreciated help me be happy

@BurkovBA
Copy link
Owner

Ok, this schema design looks almost ok, except by the fact that I don't understand, what Document is Comments embedded into? Should it be embedded into Project?

Note a couple of edits of mine. I used triple backticks (```) to format multiline code (not single backticks) and also suggest to rename Projects -> Project and Comments -> Comment.

As for authentication. You are planning to design a REST api for your Project document, right? Project should be allowed for edit only to authenticated users, may be just for owner or something like this. You need a ViewSet and a Serializer for Project in that case. Like in example or in this paper:

from users.authentcation import TokenAuthentication
from rest_framework import permissions
from rest_framework_mongoengine.views import ModelViewSet
from rest_framework_mongoengine.serializers import DocumentSerializer

class ProjectViewSet(ModelViewSet):
    permission_classes = (permissions.IsAuthenticated, )  # IsAdminUser?
    authentication_classes = (TokenAuthentication, )
    lookup_field = 'id'
    serializer_class = ProjectSerializer

    def get_queryset(self):
        return Project.objects.all()

class ProjectSerializer(mongoserializers.DocumentSerializer):
    class Meta:
        model = Project
        fields = '__all__'

See https://github.com/BurkovBA/django-rest-framework-mongoengine-example and copy-paste pieces of code, you need, from it.

@MohamedShawky
Copy link
Author

Hi @BurkovBA
in the user app
how to allow POST data to DRF-ME
when i run project that appears to me

HTTP 401 Unauthorized
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
WWW-Authenticate: Token

{
"detail": "Authentication credentials were not provided."
}
Uploading post.PNG…

@BurkovBA
Copy link
Owner

BurkovBA commented May 4, 2017

@MohamedShawky

Mohamed, are you passing your authentication Token with your request in a Authorization header of your request like this^

Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a

It is not just a cookie, you need to set this header in your request by hand.

Unfortunately, this makes Browsable API unusable, cause you can't pass the Token right in your browser: http://stackoverflow.com/questions/35601130/django-rest-framework-using-tokenauthentication-with-browsable-api.

This is very sad, I'll take a look what we can do about it. May be, you could add BasicAuthentication or SessionAuthentication to authentication_classes for testing purposes, but this is a palliative solution. Sorry.
=(

Also, make sure that your viewset support POST method by design. Cause, for instance, UserViewSet in my example does not - it is a read-only.
And don't forget settings permission_classes (and possibly authentication_classes) on your viewset.

@MohamedShawky
Copy link
Author

MohamedShawky commented May 5, 2017

hi @BurkovBA
i make viewset support POST method but when posting data an error occure
which like this

Got a `ValidationError` when calling `User.objects.create()`. 
This may be because request data satisfies serializer validations but not Mongoengine`s.
 You may need to check consistency between User and UserSerializer.
If that is not the case, 
please open a ticket regarding this issue on https://github.com/umutbozkurt/django-rest-framework-mongoengine/issues

Original exception was: ValidationError (User:None) (Field is required: ['id'])

i try to solve it by remove id field from model.py and work

but there is a problem which User is not have id

can you fix this ?

and how make nested serializers

@BurkovBA
Copy link
Owner

BurkovBA commented May 5, 2017

Yes, to solve this, you need to manually add an id field to your UserSerializer:

class UserSerializer(DocumentSerializer):
    id = serializers.IntegerField(read_only=False)

    class Meta:
        model = User
        fields = '__all__'

That's an issue of Mongoengine - it expects id field to be non-writable by default (in MongoDB it's normally just mapped to _id field, which is an auto-generated ObjectId). In our case, if we want it to be a writable primary key, we need it explicitly mapped to IntegerField, corresponding to IntField in UserDocument.

@ashokpal100
Copy link

Hi @BurkovBA

i have download the project than run successfully

have enter the http://localhost:8000/api in url than show

A server error occurred. Please contact the administrator.

@BurkovBA
Copy link
Owner

@ashokpal100 Hi, this error alone is non-descriptive. Could you also specify the messages, shown in your terminal console (where you probably said python manage.py runserver)?

@ashokpal100
Copy link

thanks for the response @BurkovBA

django version problem
resolved the issue

@ashokpal100
Copy link

@BurkovBA
Hi, BurkovBA!

your project running successful. i want to create user by cmd than show error

Password:
Password (again):
Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 52, in execute
return super(Command, self).execute(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 173, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 165, in create_superuser
return self._create_user(username, email, password, **extra_fields)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 147, in _create_user
user.set_password(password)
File "/home/ashok/Desktop/django-rest-framework-mongoengine-example/project/users/models.py", line 86, in set_password
self.save()
File "/usr/local/lib/python2.7/dist-packages/mongoengine/document.py", line 287, in save
self.validate(clean=clean)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/base/document.py", line 411, in validate
raise ValidationError(message, errors=errors)
mongoengine.errors.ValidationError: ValidationError (User:None) (Field is required: ['id'])

plz let me know where i am wrong. guide me

@BurkovBA
Copy link
Owner

@ashokpal100

Hi, did you manually create an id serializer field, as I suggested previously in this post?

I'm sorry, Ashok, I can't dedicate much time to guiding anybody. I'm fully preoccupied, working on other projects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants