Design and implementation of user function
User login interface design
{ "password":"test", "email":"[email protected]" }
Routing Configuration
#在user/urls.py文件中 from django.conf.urls import url from .views import reg,login urlpatterns = [ url(r'^reg$',reg), url(r'^login$',login) ]
Login code
def login(request:HttpRequest): payload = simplejson.loads(request.body) try: email = payload['email'] password = payload['password'].encode() user = User.objects.filter(email=email).get() if bcrypt.checkpw(password,user.password.encode()):#user.password代表数据库里面的密码 #验证通过 token = gen_token(user.id) # print(token) res = JsonResponse({ 'user':{ 'user_id':user.id, 'name':user.name, 'email':user.email }, 'token':token }) res.set_cookie('Jwt',token)#演示如何设置set cookie return res else: return HttpResponseBadRequest() except Exception as e: print(e) return HttpResponseBadRequest () # where return an instance, it is not unusual class
Certified Interface
Django certification
Middleware Middleware
Reference: https://docs.djangoproject.com/en/1.11/topics/http/middleware/ # Writing-your-own-Middleware
class BlogAuthMiddleware (Object): "" " Custom middleware " "" DEF the __init__ (Self, get_response was): self.get_response = get_response was DEF the __call__ (Self, Request: the HttpRequest): # Before view function is executed # authentication Print (type ( Request), ' ~~~~ ' ) Print ( `` request.GET``) Print (of request.POST) Print (request.body) # JSON data Response = self.get_response (Request) # performed after the attempt function #TODO return the Response # To register MIDDLEWARE settings in
Set Middleware Reference: https://www.cnblogs.com/sui776265233/p/9664642.html
Decorator *
#user/urls.py from django.conf.urls import url from .views import reg,login,test#,testMiddle urlpatterns = [ url(r'^test',test), ]
# User / the views.py AUTH_EXPIRE. 8 * 60 * 60 = DEF the authenticate (View): DEF warpper (Request: the HttpRequest): # Custom JWT header payload request.META.get = ( ' HTTP_JWT ' ) # will be prefixed HTTP_ and all upper IF not payload: # None did not get the authentication failure return the HttpResponse (Status = 401 ) the try : # decoded payload = jwt.decode (payload, settings.SECRET_KEY, algorithms = [ ' HS256 ' ]) Print (payload) except : return HttpResponse(status=401) #验证过期时间 current = datetime.datetime.now().timestamp() if (current - payload.get('timestamp',0)) > AUTH_EXPIRE: return HttpResponse(status=401) print('*'*30) try: user_id = payload.get('user_id') user = User.objects.filter(pk=user_id).get() request.user = User Print ( ' * ' * 30 ) the except Exception AS E: Print (E) return the HttpResponse (Status = 401 ) RET = View (Request) # call the view function return RET return warpper @authenticate DEF Test (Request: the HttpRequest): # very free application that requires authentication on the view function return HttpResponse ( ' the Test ' )
JWT expired question
import jwt import datetime import threading event = threading.Event() key = 'magedu' data = jwt.encode({'name':'tom','age':20,'exp':int(datetime.datetime.now().timestamp()+3)},key) print(jwt.get_unverified_header(data)) try: while not event.wait(1): print(jwt.decode(data,key))# Expired, check throws an exception Print (datetime.datetime.now () timestamp ().) The except jwt.ExpiredSignatureError AS E: Print (E)
# User.views.py AUTH_EXPIRE = 60. 8 * 60 * # DEF gen_token (user_id): "" " generate token " "" return jwt.encode ({ # increasing timestamp token or determining whether a retransmission log back ' user_id ' : user_id, ' exp ' : (. datetime.datetime.now () timestamp () + 500) int # require rounding }, settings.SECRET_KEY, ' HS256 ' ) .decode () # string DEF the authenticate (View): DEF warpper (Request: the HttpRequest): # custom JWT header payload = request.META.get(' HTTP_JWT ' ) # will be prefixed HTTP_ all uppercase and Print (payload, ' # ' * 10 ) IF Not payload: # None did not get the authentication failure return the HttpResponse (Status = 401 ) the try : # decoded payload = jwt. decode (payload, settings.SECRET_KEY, algorithms = [ ' HS256 ' ]) Print (payload) the except : return the HttpResponse (Status = 401 ) the try : user_id Payload.get = ( ' user_id ' ) User = User.objects.filter (PK = user_id) .get () the request.user = User # if correct injection User Print ( ' * ' * 30 ) the except Exception AS E: Print (E) return the HttpResponse (Status = 401 ) RET = view (Request) # call the view function return RET return warpper