Thursday 10 September 2015

OAuth2 setup in restapi and authentication with api

OAuth2 setup in restapi and authentication with api 

Firstly setup the restframework
After setup please follow these steps

1.pip install django-oauth-toolkit

2.add ‘oauth2_provider’ to your INSTALLED_APPS setting.

3.url(r'^o/', include('oauth2_provider.urls')), to your urls.py

4.Add the following to your settings.py module:

    OAUTH2_PROVIDER = {
        # this is the list of available scopes
        'SCOPES': ['read', 'write', 'groups']
    }

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        ),
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        )
    }

5.Run python manage.py syncdb

6.open backend admin (127.0.0.1:8000/admin)

7.Step 3: Register an application

    To obtain a valid access_token first we must register an application.

    From the admin go to oauth2_provider > applications > Add Application. Fill the form with the following data:

        User: your current user
        Client Type: confidential
        Authorization Grant Type: Resource owner password-based
       
    Save your app!

8.Get your token and use your API

At this point we’re ready to request an access_token. Open your shell
    Note = TO get client id and client secret, go to the admin panel and then oauth2_provider > applications >select application
   
    syntax = curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" http://<client_id>:<client_secret>@localhost:8000/o/token/
   
    eg. =  curl -X POST -d "grant_type=password&username=admin&password=admin" http://lh4RIKR2Cn95LHVOYLMddT1RAxDgHRDIEwPyR61g:82aVoSzfHyoWEguSBhp4ZHXigowzuLJS45kI7j3l6Flz5k42LDcBHiKSTl0fJ5OhijtIxY2sNPUDihKSQKna1eaEXt3dTG69u3eLNq6EJqqJdGfJRgnzFSSaHPU2NVqT@192.168.1.6:8000/shopping/o/token/

Response should be something like:

    {
        “access_token”: “<your_access_token>”, “token_type”: “Bearer”, “expires_in”: 36000, “refresh_token”: “<your_refresh_token>”, “scope”: “read write groups”

    }
   
   
Authentication with api from front end

    def userlogin(request):
        url = 'http://192.168.1.6:8000/shopping/o/token/'
        form = LoginForm
        template_name = 'index.html'
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            cd = {}
            cd['username'] = username
            cd['password'] = password
            cd['client_id'] = 'lh4RIKR2Cn95LHVOYLMddT1RAxDgHRDIEwPyR61g'
            cd['client_secret'] = '82aVoSzfHyoWEguSBhp4ZHXigowzuLJS45kI7j3l6Flz5k42LDcBHiKSTl0fJ5OhijtIxY2sNPUDihKSQKna1eaEXt3dTG69u3eLNq6EJqqJdGfJRgnzFSSaHPU2NVqT'
            cd['grant_type'] = 'password'
           
            r = requests.post(url, data=cd)       
            if r:
                data = r.json()
                token = data['access_token']
                request.session['token'] = 'Bearer ' + token
                headers = {'Authorization': request.session['token']}
                s = requests.get('http://192.168.1.6:8000/shopping/registration/', headers=headers)
               
                data2  = s.json()
                for d in data2:
                    if d['username'] == username:
                        print username
                        return HttpResponse("Working") 

Monday 7 September 2015

Reset password/Forgot password/Lost password in django

To recover your lost password in Django we have the following steps i am following the steps from Here- First we should also know that how does this works-
  1. On clicking Forgot/Lost Password link on your template it'll redirect to a page where you have to enter your registered user email id.
  2. If email id is valid it'll send an email with a update password link.
  3. On clicking that link you have to submit your new password twice.
  4. On successful password update  it'll redirect with Log-in link.


STEP 1:- Before begin anything consider we have setup our project like there is a project and an app, and copy the required template from Django's core template to your own project template system, copy this whole registration folder into our template. we can copy the folder from-
"Our_project/lib/python2.7/site-packages/django/contrib/admin/templates/registration".


It'll contain following files-


/django/contrib/admin/templates/registration/password_reset_form.html
/django/contrib/admin/templates/registration/password_reset_done.html
/django/contrib/admin/templates/registration/password_reset_confirm.html
/django/contrib/admin/templates/registration/password_reset_complete.html
/django/contrib/admin/templates/registration/password_reset_email.html
 

STEP 2 :- setting.py:- Configure the smtp/mail server in setting.py

if DEBUG:
    EMAIL_HOST = 'localhost'
    EMAIL_PORT = 1025
    EMAIL_HOST_USER = ''
    EMAIL_HOST_PASSWORD = ''
    EMAIL_USE_TLS = False
    DEFAULT_FROM_EMAIL = 'testing@example.com'


This is the default server of the local host, To activate this we have to run a command i.e.
"python -m smtpd -n -c DebuggingServer localhost:1025"

Beside this we can add server detail as same as below:-

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'username@gmail.com'
EMAIL_HOST_PASSWORD = 'gmailPassword'
DEFAULT_FROM_EMAIL = 'username@gmail.com'
DEFAULT_TO_EMAIL = 'username@gmail.com'

<!-- OR -->
EMAIL_HOST = 'mail.xyz.com'
EMAIL_HOST_USER = 'username@xyz.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 25
EMAIL_USE_TLS = False


STEP 3:- Give URL to your html for lost password link as below-

<a class="to_forget" href="{% url 'password_reset' %}">Lost your password?</a>
STEP 4:- Add Few URLs in your main project.url.py as below
   
url(r'^user/password/reset/$', 'django.contrib.auth.views.password_reset', {'post_reset_redirect' : '/user/password/reset/done/'}, name="password_reset"),
url(r'^user/password/reset/done/$', 'django.contrib.auth.views.password_reset_done'),
url(r'^user/password/reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', {'post_reset_redirect' : '/user/password/done/'}),
url(r'^user/password/done/$', 'django.contrib.auth.views.password_reset_complete'),


STEP 5:- Now in template/registration/Password_reset_email.html
replace {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
with    {{ domain }}{% url 'django.contrib.auth.views.password_reset_confirm' uidb64=uid token=token %}

Now we're able to update our lost password,
in the last we can change template/registration/password_reset_complete.html with our login link.