Аутентификация используется для защиты нашего приложения. В этом руководстве я покажу вам, как аутентифицировать ваши приложения с помощью токенов, которые будут храниться в нашем браузере.
Шаг № 1: Перейдите в свой cmd и введите
vue create ui
установите любую версию vue после завершения установки внутри вашей папки vue install
npm install vue-notification axios bootstrap
Вот как будет выглядеть наша структура папок
просто создайте авторизацию папки в своем компоненте
в файле router.js добавьте этот код
{ path: "/login", name: "login", component: () => import("../components/auth/Login.vue") }, { path: "/register", name: "register", component: () => import("../components/auth/Register.vue") }, { path: "/forgot-password", name: "forgot-password", component: () => import( "../components/auth/ForgotPassword.vue" ) }, { path: "/reset", name: "reset", component: () => import( "../components/auth/Reset.vue") }, { path: "/profile", name: "profile", component: () => import( "../components/auth/Profile.vue") },
Шаг № 2: Добавьте это в свои коды в свои файлы vue.
добавьте это в register.vue
<div class=""> <div class=""> <div class="card"> <form autocomplete="off" class="form" id="formLogin" name="formLogin" role="form" > <h2 class="title"> Register</h2> <div class="form-group"> <label for="uname1">email</label> <input class="form-control" id="uname1" v-model="email" name="uname1" required="" type="text" > </div> <div class="form-group"> <label>Password</label> <input autocomplete="new-password" class="form-control" id="pwd1" required="" v-model="password" type="password" > </div> <div class="form-group"> <label for="uname1">name</label> <input class="form-control" id="uname1" v-model="name" name="uname1" required="" type="text" > </div> <button @click="submit" class="cta-btn" type="button" >Register</button> </form> <p class="subtitle"> Have an account? <router-link to="/login">Login</router-link> </p> </div> </div> </div>
ваш тег скрипта
<script> import axios from 'axios' export default { data: () => ({ valid: true, name: '', email: '', password: '', emailRules: [ v => !!v || 'E-mail is required', v => /\S+@\S+\.\S+/.test(v) || 'E-mail must be valid' ] }), methods: { async submit() { const response = await axios .post('http://localhost:5000/api/auth/signup', { name: this.name, email: this.email, password: this.password }) .then(response => { this.$notify(`success`) this.$router.push({ name: 'login' }) }) .catch(err => { const message = err.response.data.message this.$notify('Oh oo!', `${message}`, 'error') }) }, clear() { this.$refs.form.reset() } } } </script>
Добавьте это в свой компонент входа
<div class=""> <!-- form card login --> <div class=""> <div class="card"> <form autocomplete="off" class="form" id="formLogin" name="formLogin" role="form" > <h2 class="title"> Log in</h2> <div class="form-group"> <label for="uname1">email</label> <input class="form-control" id="uname1" v-model="email" name="uname1" required="" type="text" > </div> <div class="form-group"> <label>Password</label> <input autocomplete="new-password" class="form-control" id="pwd1" required="" v-model="password" type="password" > </div> <button @click="submit" class="cta-btn" type="button" >Login</button> </form> <p class="subtitle">Don't have an account? <router-link to="/register">register</router-link> </p> <p class="subtitle">Forgot password? <router-link to="/forgot-password">forgot-password</router-link> </p> </div> </div> </div>
тег скрипта
<script> import axios from 'axios' export default { data: () => ({ valid: true, email: '', password: '', confirm_password: '', }), methods: { async submit() { const response = await axios .post('http://localhost:5000/api/auth/login', { email: this.email, password: this.password }) .then(response => { //get the token const token = response.data.token // store the token in the browser localStorage.setItem('token', response.data.token) this.$notify(`signed in`) this.$router.push('/profile') }) .catch(err => { const message = err.response.data.message this.$notify('Oh oo!', `${message}`, 'error') }) }, clear() { this.$refs.form.reset() } } } </script>
в profile.vue добавить этот файл
<template> <div> {{ name }} <div @click="logout" v-if="token" > logout </div> </div> </template> <script> import axios from "axios"; export default { name: "app", components: {}, data() { return { name: "", email: "", token: null, }; }, mounted() { // get the token from the browser const token = localStorage.getItem("token"); this.token = token axios .get("http://localhost:5000/api/auth/user", { headers: { Authorization: "Bearer" + token, "x-access-token": token } }) .then(res => { // console.log(res); this.name = res.data.user.name; this.email = res.data.user.email; }) .catch(error => { console.log(error); }); }, methods: { logout() { localStorage.clear(); this.$router.push("/login"); } } }; </script>
добавьте это в файл забытого пароля.vue
<form @submit.prevent="handleSubmit" autocomplete="off" class="form" role="form" > <div class="form-group"> <label for="inputPasswordOld">enter email</label> <input class="form-control" id="inputPasswordOld" required="" type="email" v-model="email" > </div> <div class="form-group"> <button class="btn btn-success btn-lg float-right" type="submit" >Send</button> </div> {{message}} </form> <script> import axios from "axios"; export default { data() { return { email: "", message: "" }; }, methods: { async handleSubmit() { const response = await axios .post("http://localhost:5000/api/auth/forgotPassword", { email: this.email }) .then(response => { console.log(response); this.message = response.data.message; }) .catch(err => console.log(err)); console.log(response); }, clear() { this.$refs.form.reset(); } } }; </script>
добавьте это в свой reset.vue
<form @submit.prevent="handleSubmit" autocomplete="off" class="form" role="form" > <div class="form-group"> <label for="inputPasswordOld">Change Password</label> <input class="form-control" id="inputPasswordOld" required="" type="password" v-model="password" > </div> <div class="form-group"> <button class="btn btn-success btn-lg float-right" type="submit" >Save</button> </div> {{message}} </form> <script> import axios from "axios"; export default { data() { return { password: "", message: "" }; }, methods: { async handleSubmit() { const response = await axios .post("http://localhost:5000/api/auth/updatePassword", { password: this.password, token: this.$route.query.token }) .then(response => { // console.log(response); this.message = response.data.message; }) .catch(err => console.log(err)); console.log(response); }, clear() { this.$refs.form.reset(); } } }; </script>
вот как вы создаете и храните токены из бэкэнда