Be token based authentication restframework

  Under normal circumstances, into the web site home page needs to be token or other authentication, you can not view the contents of the home page without logging in, and after the user enters a user name and password, verify successful, the background will return a token, with for the next visit to the home page or other pages for user authentication upon successful authentication can be visited.

1, users access token

User sends the username and password to verify the background API and access token.

Methods: { 

      loginSubmit (formName) { 
        the this $ refs [formName] .validate (the async (Valid) =>. {
           IF (Valid) { 
            const RES = the await the this $ http.post ( 'Login',. the this .form); 
            Data {const, Meta: {Message, code}} = res.data;
             IF (code 2000 === ) { 

              // Get token, the token value stored in localStorage 
              localStorage.setItem ( 'token' , data.token); 

              // Jump directly to the main page after authentication is successful 
              this $ router.push ({name: 'Home'. });
               // successful login prompt 
              this. $ message.success (Message) 
            } the else {
               the this $ message.warning (Message). 
            } 

          } the else {
             the this $ message.warning ( "user name or password is not blank." ) 
          } 
        }); 
      } 
    },

2, the background verification

class the LoginView (APIView): 
    authentication_classes = []   # landing page-free, the rest of the global configuration has 

    DEF POST (Self, Request, * args, ** kwargs): 

        RET = {
             " Data " : {},
             " Meta " : {
                 " code " : 2001 ,
                 " Message " : " user name or password error " 
            } 
        } 
        USER_OBJ = json.loads (STR (request._request.body, encoding = ' UTF8 ')) 
        Username = user_obj.get ( ' username ' ) 
        password = user_obj.get ( ' password ' )
         IF username and password: 
            obj = UserInfo.objects.filter ( 
                username = username, password = password) .first ()
             IF obj: 

                token = get_md5 (username)
                 # automatically go to check the database, if not create, or update token 
                UserToken.objects.update_or_create (the User = obj, Defaults = { ' token ': token})
  
                ret["data"]["username"] = username
                ret["data"]["password"] = password
                ret["data"]["token"] = token

                ret["meta"]["code"] = 2000
                ret["meta"]["message"] = "登陆成功"
            else:
                pass
        else:
            pass
        return HttpResponse(json.dumps(ret, ensure_ascii=False))

 

Guess you like

Origin www.cnblogs.com/shenjianping/p/11448160.html