NuxtjsとDjango RESTフレームワークによるユーザ認証の設定[パート‐2]


チュートリアルは2つの部分に分割されている-バックエンドを設定し、フロントエンドを設定します.これがPART - 2です.
repoには二つの分岐があります.part-1 and part-2 . part-1 このチュートリアルのファイルを含みます.part-2 含む
このチュートリアルおよび次のファイル.
チュートリアルパート1 :
ギタブレポhttps://github.com/IgnisDa/django-nuxtjs-authentication
注:私は簡潔を維持するためにHTMLのほとんどを省略します.あなたは
完全なファイルを見るために倉庫に相談してください.

必要条件
  • Djangoレストフレームワークに精通して
  • Nuxt Authに関する知識

  • フロントエンドの設定
    認証を既存のプロジェクトに統合する場合は
    使用するプロジェクトに必要なモジュールnpm or yarn . ジャストランnpm install @nuxtjs/auth @nuxtjs/axiosfrontend/ ディレクトリ.
    あなたがゼロから始めているならば、あなたはこれらのステップに従うことができます.
    $ npx create-nuxt-app frontend # in the root directory `nuxtjs+drf-user-auth/`
    
    Generating Nuxt.js project in frontend
    ? Project name: frontend
    ? Programming language: JavaScript
    ? Package manager: Npm
    ? UI framework: Vuetify.js
    ? Nuxt.js modules: Axios
    ? Linting tools: ESLint, Prettier
    ? Testing framework: Jest
    ? Rendering mode: Single Page App
    ? Deployment target: Server (Node.js hosting)
    ? Development tools: jsconfig.json (Recommended for VS Code if you're not using typescript)
    
    私は使用されますVuetify 私のUIフレームワークとして
    あなたが欲しい他.しかし、あなたが他の何かを使うならば
    Buefy , 別のHTMLタグを使用する必要があります.例えば、Vuetifyのボタン<v-btn @click="greetPerson()">Click Me!</v-btn>
    執筆<b-button @click="greetPerson()">Click Me!</b-button> イン
    不吉な.しかしながら、Vueディレクティブと一般APIは同じままです.
    まずはAuthモジュールを使用して設定を設定します.
    // frontend/nuxtjs.config.js
    export default {
    // [...other settings...]
        modules:{
            // [...other stuff...]
           '@nuxtjs/axios',
           '@nuxtjs/auth',
       },
        axios: {
           baseURL: 'http://127.0.0.1:8000/',
       },
        auth: {
        strategies: {
          local: {
            endpoints: {
              login: {
                url: 'token/login/',
                method: 'post',
                propertyName: 'auth_token',
              },
              logout: { url: 'token/logout/', method: 'post' },
              user: {
                url: 'accounts/data/',
                method: 'get',
                propertyName: false,
              },
            },
            tokenType: 'Token',
            tokenName: 'Authorization',
          },
          redirect: {
            login: '/login',
            home: '/',
          },
        },
      },
    }
    
    次にファイルを作成するfrontend/store/index.js 保存します.ファイヤーアップ
    ランニングによる開発サーバnpm run devfrontend/ディレクトリ.訪問http://127.0.0.1:3000/ あなたのブラウザで.
    次のようにしました.
  • 追加axios モジュールを設定します.このモジュールはrequests Pythonでよく使うパッケージです.
  • 追加auth ユーザ認証のためのバックエンドに必要なリクエストを自動的に送信する設定にモジュールを設定します.
  • 現在ログインしているユーザのデータをVuex ストア.だから我々はfrontend/store/index.js を有効にします.
  • 我々はいくつかの変更を行いますfrontend/layouts/default.vue .
    <!-- layouts/default.vue -->
    <!-- Add these lines somewhere near the middle so that these buttons are visible on the navbar -->
    <template>
    <!-- Other stuff -->
       <div class="authentication-buttons">
          <div v-if="$auth.loggedIn">
             {{ $auth.user.email }}
             <v-btn icon to="/logout" class="logout-btn">
                <v-icon light @click="$auth.logout()">mdi-logout</v-icon>
             </v-btn>
          </div>
          <div v-else>
             <v-btn icon to="/login" class="login-btn">
                <v-icon>mdi-login</v-icon>
             </v-btn>
             <v-btn icon to="/register" class="register-btn">
                <v-icon>mdi-account-key-outline</v-icon>
             </v-btn>
          </div>
       </div>
    <!-- Other stuff -->
    </template>
    
    <script>
    export default {
      // Some more stuff
    }
    </script>
    
    我々はv-if 現在のユーザがログインしているかどうかを調べるディレクティブ.
    がある場合は、ログアウトボタンを表示する
    ボタンを使用して登録ボタンv-else ディレクティブ.
    次に、ログイン、ログアウト、レジスターのページ(ルート)を作りましょう.
    <!-- pages/login.vue -->
    <!-- This contains the login form. You should also add some custom validation yourself. -->
    <template>
      <div class="login-page">
        <v-layout flex align-center justify-center>
          <v-flex xs6 sm6 elevation-6>
            <v-card>
              <v-card-title flex align-center justify-center>
                <h1>Login</h1>
              </v-card-title>
              <v-card-text class="pt-4">
                <div>
                  <v-form ref="form">
                    <v-text-field
                      v-model="userData.email"
                      label="Enter your e-mail address"
                      counter
                      required
                    ></v-text-field>
                    <v-text-field
                      v-model="userData.password"
                      label="Enter your password"
                      :append-icon="
                        userData.showPassword ? 'mdi-eye-off' : 'mdi-eye'
                      "
                      :type="userData.showPassword ? 'text' : 'password'"
                      required
                      @click:append="userData.showPassword = !userData.showPassword"
                    ></v-text-field>
                    <v-layout justify-space-between>
                      <v-btn @click="logInUser(userData)">
                        Login
                      </v-btn>
                      <a href="?">Forgot Password</a>
                    </v-layout>
                  </v-form>
                </div>
              </v-card-text>
            </v-card>
          </v-flex>
        </v-layout>
      </div>
    </template>
    
    <script>
    export default {
      data: () => ({
        userData: { email: '', password: '', showPassword: false },
      }),
      methods: {
        async logInUser(userData) {
          try {
            await this.$auth.loginWith('local', {
              data: userData,
            })
            console.log('notification successful')
          } catch (error) {
            console.log('notification unsuccessful')
          }
        },
      },
    }
    </script>
    
    このページでは、ログインフォームを作成しましたemail and password フィールド.
    があるuserData フォームのすべてのプロパティを格納するオブジェクトです
    これを検証し、検証したデータを
    バックエンド.ログインしたボタンをクリックすると、async関数logInUser() が実行される.これはnuxtjsを使用します.auth モジュールを送信する
    POSTリクエストuserData to token/login/ では、
    ログインを自動的に行い、ログイントークンを返しますauth_token . このauth_token 更なる使用のためにVUEX店に保管されます
    その後.さらに、新しい要求が送られますaccounts/data/ そのとき
    ログインしているユーザに関するすべてのデータを返すemail , id , first_name ,
    ログアウトボタンなど既に動作します.それをクリックすると、それはauthモジュール関数$auth.logout() . これは単にauth_token から
    メモリとフラッシュアウト$auth.user オブジェクト.
    だからログインとログアウト機能が動作している!ああ!
    今すぐ登録機能を取得しましょう.これはかなりでしょう
    簡単.
    <!-- pages/register.vue -->
    <template>
      <div class="register-page">
        <v-container>
          <v-layout flex align-center justify-center>
            <v-flex xs6 sm6 elevation-6>
              <v-card>
                <v-card-title flex align-center justify-center>
                  <h1>Register</h1>
                </v-card-title>
                <v-card-text class="pt-4">
                  <div>
                    <v-form ref="form">
                      <v-text-field
                        v-model="userData.email"
                        label="Enter your e-mail address"
                        counter
                        required
                      ></v-text-field>
                      <v-text-field
                        v-model="userData.password"
                        label="Enter your password"
                        required
                        :append-icon="
                          userData.showPassword ? 'mdi-eye' : 'mdi-eye-off'
                        "
                        :type="userData.showPassword ? 'text' : 'password'"
                        @click:append="
                          userData.showPassword = !userData.showPassword
                        "
                      ></v-text-field>
                      <v-text-field
                        v-model="userData.password2"
                        label="Confirm password"
                        :append-icon="
                          userData.showPassword2 ? 'mdi-eye' : 'mdi-eye-off'
                        "
                        :type="userData.showPassword2 ? 'text' : 'password'"
                        required
                        @click:append="
                          userData.showPassword2 = !userData.showPassword2
                        "
                      ></v-text-field>
                      <v-layout justify-space-between>
                        <v-btn @click="signUp(userData)">
                          Register
                        </v-btn>
                        <a href="">Forgot Password</a>
                      </v-layout>
                    </v-form>
                  </div>
                </v-card-text>
              </v-card>
            </v-flex>
          </v-layout>
        </v-container>
      </div>
    </template>
    
    <script>
    export default {
      data: () => ({
        userData: {
          email: '',
          password: '',
          password2: '',
          showPassword: false,
          showPassword2: false,
        },
      }),
      methods: {
        async signUp(registrationInfo) {
          await this.$axios
            .$post('accounts/users/', registrationInfo)
            .then((response) => {
              console.log('Successful')
            })
            .catch((error) => {
              console.log('errors:', error.response)
            })
          this.$auth.loginWith('local', {
            data: registrationInfo,
          })
        },
      },
    }
    </script>
    
    ユーザーがフォームの詳細を入力するとすぐに、レジスタをクリックします
    ボタン、機能signUp() が発射される.使用axios モジュール、ポスト
    リクエストを送信するaccounts/users . データが有効であると仮定すると、ユーザは
    データベースで作成されます.次に、auth モジュールを再度使用するログイン
    我々がログインページに以前にしたのと同じ論理login.vue . ログアウト
    機能は前と同じです.

    結論
    だから、今あなたが認証している新機能をどのように計画しています
    実装?
    私は、このチュートリアルに従う時間をとって、あなたにすべてに感謝します、そして、私は私がそうすることができることを望みます
    将来的にあなたを助ける.ではね!