Last active
May 4, 2018 11:24
-
-
Save vivekrk1992/b20aa6500438e698aec859da1b3fe5a8 to your computer and use it in GitHub Desktop.
Create Token Authentication in Django using ionic 3 login and logout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
install rest frame work | |
``` | |
pip install djangorestframework | |
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INSTALLED_APPS = ( | |
... | |
"rest_framework", | |
"rest_framework.authtoken", | |
... | |
) | |
... | |
... | |
REST_FRAMEWORK = { | |
'DEFAULT_AUTHENTICATION_CLASSES': ( | |
'rest_framework.authentication.TokenAuthentication', | |
'rest_framework.authentication.BasicAuthentication', | |
'rest_framework.authentication.SessionAuthentication', | |
), | |
'DEFAULT_PERMISSION_CLASSES': [ | |
'rest_framework.permissions.IsAuthenticated', | |
] | |
} | |
# migrate after adding these lines |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework.decorators import api_view, permission_classes | |
from django.contrib.auth import authenticate, logout, login | |
from rest_framework.authtoken.models import Token | |
from rest_framework.permissions import AllowAny | |
@api_view(['POST', 'GET', 'PUT']) | |
@permission_classes((AllowAny, )) # allow user without header authorization | |
def mobile_login(request): | |
if request.method == 'POST': | |
user = authenticate(username=request.data['user_name'], password=request.data['password']) | |
if user is not None: | |
if user.is_active: | |
login(request, user) | |
token = Token.objects.create(user=user) | |
return Response({'token': str(token)}) | |
else: | |
return Response(status=status.HTTP_401_UNAUTHORIZED) | |
@api_view(['GET', 'POST']) | |
def mobile_logout(request): | |
if request.method == 'POST': | |
Token.objects.get(user_id=request.user.id).delete() | |
return Response(status=status.HTTP_200_OK) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf.urls import * | |
from main import views | |
from rest_framework.urlpatterns import format_suffix_patterns | |
urlpatterns = [ | |
... | |
# mobile login | |
url(r'^mobile/login/$', views.mobile_login), | |
url(r'^mobile/logout/$', views.mobile_logout), | |
... | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ion-content padding> | |
<form [formGroup]="login_form" (ngSubmit)="logIn()"> | |
<ion-list class="align-center"> | |
<ion-item> | |
<ion-label floating>User Name</ion-label> | |
<ion-input type="text" formControlName="user_name"></ion-input> | |
</ion-item> | |
<ion-item> | |
<ion-label floating>Password</ion-label> | |
<ion-input type="password" formControlName="password"></ion-input> | |
</ion-item> | |
<button ion-button type="submit" class="button-center">Log In</button> | |
</ion-list> | |
</form> | |
</ion-content> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { IonicPage, NavController, NavParams } from 'ionic-angular'; | |
import { FormBuilder, FormGroup} from '@angular/forms'; | |
import { TabsPage } from '../tabs/tabs' | |
import { HttpServerServiceProvider } from '../../providers/http-server-service/http-server-service' | |
@IonicPage() | |
@Component({ | |
selector: 'page-login', | |
templateUrl: 'login.html', | |
}) | |
export class LoginPage { | |
login_form: FormGroup; | |
constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, private httpServerServiceProvider:HttpServerServiceProvider) { | |
this.login_form = this.formBuilder.group({ | |
user_name: [''], | |
password: [''], | |
}); | |
} | |
ionViewDidLoad() { | |
console.log('ionViewDidLoad LoginPage'); | |
} | |
logIn() { | |
console.log('login function'); | |
console.log(this.login_form.value); | |
this.httpServerServiceProvider.login(this.login_form.value).subscribe( | |
(data) => { | |
this.httpServerServiceProvider.setToken(data.token); | |
this.navCtrl.setRoot(TabsPage) | |
} | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { Http, Headers } from '@angular/http'; | |
import 'rxjs/add/operator/map'; | |
@Injectable() | |
export class HttpServerServiceProvider { | |
private token: any; | |
headers: any; | |
base_url: string = "http://127.0.0.1:8000/"; | |
constructor(public http: Http) { | |
this.headers = new Headers(); | |
} | |
... | |
// login | |
login(data) { | |
return this.http.post(this.base_url+"main/mobile/login/", data, {headers: this.headers}) | |
.map(res => res.json()); | |
} | |
logout() { | |
return this.http.post(this.base_url+'main/mobile/logout/', {'user_id':1}, {headers: this.headers}) | |
.map(res => console.log(res)); | |
} | |
setToken(token) { | |
this.headers.append('Authorization', 'Token ' + token); | |
} | |
eraseToken() { | |
this.token = ''; | |
this.headers = new Headers(); | |
} | |
... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
logout() { | |
this.httpServerServiceProvider.logout().subscribe( | |
(data) => { | |
this.httpServerServiceProvider.eraseToken(); | |
this.navCtrl.setRoot(LoginPage); | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment