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.

Wednesday, 24 June 2015

How to configure Mezzanine with MySql and wsgi ?

1. Firstly write these commands on terminal

    1.sudo mkdir /var/www/lyfstyle/
    2.sudo mkdir /var/www/lyfstyle/apache

2. sudo vi /var/www/lyfstyle/apache/apache.wsgi
    --Paste this code in apache.wsgi--

    import os
    import sys
   
    path = '/var/www'
    if path not in sys.path:
        sys.path.insert(0, '/var/www/lyfstyle')
        sys.path.append('/var/www/lyfstyle/lyfstyle_env/mezzanine_lyfstyle')
   
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
   
    import django.core.handlers.wsgi
    application = django.core.handlers.wsgi.WSGIHandler()

OR 

import os
import sys

path = '/var/www/lyfstyle'

if path not in sys.path:
    sys.path.insert(0, '/var/www/lyfstyle/mezzanine_lyfstyle')
    sys.path.append('/var/www/lyfstyle')

os.environ['DJANGO_SETTINGS_MODULE'] = 'mezzanine_lyfstyle.settings'

#import django.core.handlers.wsgi
#application = django.core.handlers.wsgi.WSGIHandler()

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


3. Open .conf file by this command ('sudo nano /etc/apache2/sites-available/000-default.conf')
    #And Paste this code   

    listen 8080
    <virtualHost *:8080>
        ServerName dev.lyfstyle
        DocumentRoot /var/www/lyfstyle/mezzanine_lyfstyle
   
        AliasMatch ^/([^/]*\.css) /var/www/lyfstyle/mezzanine_lyfstyle/static/css/
       # create alias for media and static directories
        Alias /media/ /var/www/lyfstyle/mezzanine_lyfs104.236.21.57tyle/media/
        Alias /static/ /var/www/lyfstyle/mezzanine_lyfstyle/static/
   
        <Directory /var/www/lyfstyle/mezzanine_lyfstyle/static>
            Order deny,allow
            Allow from all
        </Directory>
   
        <Directory /var/www/lyfstyle/lyfstyle_env/mezzanine_lyfstyle/media>
            Order deny,allow
            Allow from all
        </Directory>
   
        <Directory /var/www/lyfstyle/mezzanine_lyfstyle>
            Order allow,deny
            Allow from all
        </Directory>
   
        WSGIDaemonProcess mysite.local processes=2 threads=15 display-name=%{GROUP}
        WSGIProcessGroup mysite.local
   
        WSGIScriptAlias /  /var/www/lyfstyle/apache/apache.wsgi
   
    </VirtualHost>

4.After run this command:
   a. sudo a2enmod wsgi


5.  After create Project:
    a. mezzanine-project mezzanine_lyfstyle
    b. cd mezzanine_lyfstyle
    c. python manage.py syncdb
    d. python manage.py collecttemplates
    e. python manage.py collectstatic

6. If you want to change Database like Mysql, sqlite, etc,
   a. open mezzanine_lyfstyle (folder)
   b. open local_settings.py
   c. Than replace this line
      ENGINE": "django.db.backends.sqlite3"
      by
      ENGINE": "django.db.backends.mysql"
     
      And Enter these Settings
     
      NAME: "DBName create in phpmyadmin",
   
      USER: "Username of phpmyadmin",
   
      PASSWORD: "Password of phpmyadmin",


Wednesday, 18 February 2015

How to configure Flask with WSGI ?

# Configure Flask with WSGI

1.Install and Enable mod_wsgi

sudo apt-get install libapache2-mod-wsgi python-dev

#To enable mod_wsgi, run the following command: 
sudo a2enmod wsgi  

2. Creating a Flask App

a. cd /var/www 
b. sudo mkdir FlaskApp
c. cd FlaskApp
d. sudo mkdir FlaskApp
e .cd FlaskApp
f .sudo mkdir static templates    
 

3.Now, create the __init__.py file that will contain the flask application logic.

sudo nano __init__.py 
 
#Add following logic to the file:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
    return "Hello, I love Digital Ocean!"
if __name__ == "__main__":
    app.run() 

4.Configure and Enable a New Virtual Host

sudo nano /etc/apache2/sites-available/FlaskApp (for older ubuntu version)
sudo nano /etc/apache2/sites-available/FlaskApp.conf (for 13+ ubuntu version) 

#Add the following lines of code to the file to configure the virtual host.
<VirtualHost *:8080>
  ServerName localhost
  ServerAdmin admin@mywebsite.com
  WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
  <Directory /var/www/FlaskApp/FlaskApp/>
   Order allow,deny
   Allow from all
  </Directory>
  Alias /static /var/www/FlaskApp/FlaskApp/static
  <Directory /var/www/FlaskApp/FlaskApp/static/>
   Order allow,deny
   Allow from all
  </Directory>
  ErrorLog ${APACHE_LOG_DIR}/error.log
  LogLevel warn
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost> 
 
Note :- Define LISTEN port before VirtualHost

Save and close the file.

5.Enable the virtual host with the following command:

sudo a2ensite FlaskApp
 

 6.Create the .wsgi File

cd /var/www/FlaskApp
sudo nano flaskapp.wsgi 
 
Add the following lines of code to the flaskapp.wsgi file:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")

from FlaskApp import app as application
application.secret_key = '123456789' 

Save and close the file.


Now your directory structure should look like this:

|--------FlaskApp
|----------------FlaskApp
|-----------------------static
|-----------------------templates
|-----------------------__init__.py
|----------------flaskapp.wsgi
 

7.Than Restart the apache server following this command

sudo service apache2 restart  

Tuesday, 30 December 2014

How to authenticate or login in django ?

# Authenticate or login in django

1. Open views.py

2. Import this line in views.py .
    from django.contrib.auth import authenticate, login

3. Create function
eg. 
 class Auth(View):
    def post(self, request, *args, **kwargs):
        use = request.POST['username']
        passw = request.POST['password']
        user = authenticate(username=use, password=passw)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponse(login)
                        # Redirect to a success page.
            else:
                return HttpResponse("disable")
          
                        # Return a 'disabled account' error message
        return HttpResponse("Invalid username or password ")
                # Return an 'invalid login' error message."

How to split the URL or String in django python ?

# Split the URL or String in django

1. You can split the string or url with the help of split function

eg.
     url = '127.0.0.1:8000/serverpage/forgot/4'
     stringsplit = url.split('/');
     filter = stringsplit[3]
     print(filter)
    
     Output is: 4

How to get current url path in Django python?

# Get current url path in Django

1. Use this code

    currenturl = request.get_full_path()

    print(currenturl)

* If you will use  print () then output will be shown in your terminal