Bất kỳ quyền truy cập nào vào đối tượng WebSecurity đều ném không hợp lệ, nếu. Đối tượng WebSecurity đưa ra một UnlimitedOperationException nếu
- Phương thức khởi tạo Phương thức khởi tạoInitializeDatabaseConnection[] chưa được gọi
- Thành viên đơn giản không được khởi tạo [hoặc bị vô hiệu hóa trong cấu hình trang web] không được khởi tạo [hoặc bị vô hiệu hóa trong cấu hình trang web]
Nhận xét
Khi người dùng được đăng nhập, ASP. NET sẽ đặt mã thông báo xác thực trong cookie cho phép ASP. NET đã biết về các yêu cầu tiếp theo mà người dùng đã đăng nhập
Phương thức đăng xuất [] xóa mã thông báo xác thực, có tác dụng đăng nhập người dùng. Phương thức logout[] loại bỏ mã thông báo xác thực, có tác dụng đăng xuất người dùng
Trong bài viết này, chúng ta sẽ cùng nhau xây dựng một ứng dụng đăng ký và đăng nhập đơn giản bằng Vue. js và được quản lý trạng thái với Vuex
Cấu trúc dự án với Vue. js và Vuex
Tất cả mã nguồn sẽ được để trong thư mục /src. Trong thư mực src sẽ bao gồm các tài sản, các thành phần được sử dụng cho các chức năng và màn hình, và các thư mục được chia sẻ đó là người trợ giúp, dịch vụ, cửa hàng
Người trợ giúp thư mục
Người trợ giúp thư mục sẽ chứa tất cả các tệp được sử dụng chung cho các thành phần có chức năng hỗ trợ hoặc các tệp không nằm trong thư mục nào
Tiêu đề xác thực Vue
/src/helpers/auth-header. js
Tiêu đề xác thực được trả về một tiêu đề xác thực HTTP chứa chuỗi JSON Web Token [JWT] của người dùng hiện tại đã được đăng nhập, được lấy từ bộ nhớ cục bộ hoặc cookie. Nếu người dùng không đăng nhập, nó sẽ trả về 1 đối tượng rỗng
Tiêu đề xác thực sẽ được sử dụng để tạo yêu cầu HTTP đã được xác thực đến máy chủ api sử dụng xác thực JWT
export function authHeader[] {
let user = JSON.parse[localStorage.getItem['user']];
if [user && user.token] {
return { 'Authorization': 'Bearer ' + user.token };
} else {
return {};
}
}
Bộ định tuyến Vue
Con đường. /src/người trợ giúp/bộ định tuyến. js
Bộ định tuyến Vue định nghĩa tất cả các tuyến đường cho ứng dụng, bao gồm một hàm sẽ chạy trước khi tuyến đường thay đổi để ngăn người dùng không được xác thực từ giới hạn truy cập
import Vue from 'vue';
import Router from 'vue-router';
import HomePage from '../components/HomePage'
import LoginPage from '../components/LoginPage'
import RegisterPage from '../components/RegisterPage'
Vue.use[Router];
export const router = new Router[{
mode: 'history',
routes: [
{ path: '/', component: HomePage },
{ path: '/login', component: LoginPage },
{ path: '/register', component: RegisterPage },
// nếu không sẽ chuyển đến trang home
{ path: '*', redirect: '/' }
]
}];
router.beforeEach[[to, from, next] => {
// chuyển đến trang login nếu chưa được login
const publicPages = ['/login', '/register'];
const authRequired = !publicPages.includes[to.path];
const loggedIn = localStorage.getItem['user'];
if [authRequired && !loggedIn] {
return next['/login'];
}
next[];
}]
Chỉ mục người trợ giúp Vue
Con đường. /src/người trợ giúp/chỉ mục. js
Nhóm người trợ giúp chỉ mục tệp tất cả các trình trợ giúp xuất giống nhau để có thể nhập cho các tệp khác nhau trong ứng dụng
When import ta could call
import config from 'config';
import { authHeader } from '../helpers';
export const userService = {
login,
logout,
register,
getAll,
getById,
update,
delete: _delete
};
function login[username, password] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[{ username, password }]
};
return fetch[`${config.apiUrl}/users/authenticate`, requestOptions]
.then[handleResponse]
.then[user => {
// login thành công nếu có một token jwt trong response
if [user.token] {
// lưu dữ liệu user và token jwt vào local storage để giữ user được log in trong page
localStorage.setItem['user', JSON.stringify[user]];
}
return user;
}];
}
function logout[] {
// xoá user từ local storage để log out
localStorage.removeItem['user'];
}
function register[user] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/register`, requestOptions].then[handleResponse];
}
function getAll[] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users`, requestOptions].then[handleResponse];
}
function getById[id] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function update[user] {
const requestOptions = {
method: 'PUT',
headers: { ...authHeader[], 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/${user.id}`, requestOptions].then[handleResponse];
}
function _delete[id] {
const requestOptions = {
method: 'DELETE',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function handleResponse[response] {
return response.text[].then[text => {
const data = text && JSON.parse[text];
if [!response.ok] {
if [response.status === 401] {
// tự động logout nếu response 401 được trả về từ api
logout[];
location.reload[true];
}
const error = [data && data.message] || response.statusText;
return Promise.reject[error];
}
return data;
}];
}
0export * from './router';
export * from './auth-header';
Thư mục Vue Services
Con đường. /src/dịch vụ
Dịch vụ sẽ chứa tất cả các gói kết nối http đến api phụ trợ cho ứng dụng, mỗi dịch vụ sẽ được đóng các lời gọi api cho từng loại nội dung [người dùng vd] và trả về các hàm thực hiện các chức năng CRUD,. Dịch vụ cũng có các chức năng mà không cần gọi http, vd userService. logout[] only delete item from local storage
Tôi thấy việc đóng các gói lời gọi http trong phần dịch vụ làm cho mã rõ ràng, đơn giản, dễ hiểu hơn
Dịch vụ người dùng Vue
Con đường. /src/dịch vụ/người dùng. dịch vụ. js
Dịch vụ người dùng đóng gói tất cả lời gọi api để xử lý các chức năng CRUD cho người dùng, bao gồm cả chức năng đăng nhập, đăng xuất, đăng ký. Dịch vụ chức năng này sẽ được xuất thông qua đối tượng userService
Hàm handleResponse trong dịch vụ sẽ kiểm tra nếu phản hồi http từ api là 401 _ chưa được xác thực thì người dùng sẽ tự động đăng xuất. Ở đây cũng bao gồm xử lý khi mã thông báo JWT hết hạn hoặc không được xác thực
import config from 'config';
import { authHeader } from '../helpers';
export const userService = {
login,
logout,
register,
getAll,
getById,
update,
delete: _delete
};
function login[username, password] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[{ username, password }]
};
return fetch[`${config.apiUrl}/users/authenticate`, requestOptions]
.then[handleResponse]
.then[user => {
// login thành công nếu có một token jwt trong response
if [user.token] {
// lưu dữ liệu user và token jwt vào local storage để giữ user được log in trong page
localStorage.setItem['user', JSON.stringify[user]];
}
return user;
}];
}
function logout[] {
// xoá user từ local storage để log out
localStorage.removeItem['user'];
}
function register[user] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/register`, requestOptions].then[handleResponse];
}
function getAll[] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users`, requestOptions].then[handleResponse];
}
function getById[id] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function update[user] {
const requestOptions = {
method: 'PUT',
headers: { ...authHeader[], 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/${user.id}`, requestOptions].then[handleResponse];
}
function _delete[id] {
const requestOptions = {
method: 'DELETE',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function handleResponse[response] {
return response.text[].then[text => {
const data = text && JSON.parse[text];
if [!response.ok] {
if [response.status === 401] {
// tự động logout nếu response 401 được trả về từ api
logout[];
location.reload[true];
}
const error = [data && data.message] || response.statusText;
return Promise.reject[error];
}
return data;
}];
}
Chỉ mục dịch vụ Vue
Con đường. /src/dịch vụ/chỉ mục. js
Chỉ mục dịch vụ tệp nhóm tất cả dịch vụ xuất giống nhau để có thể dễ dàng nhập vào các tệp khác.
import config from 'config';
import { authHeader } from '../helpers';
export const userService = {
login,
logout,
register,
getAll,
getById,
update,
delete: _delete
};
function login[username, password] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[{ username, password }]
};
return fetch[`${config.apiUrl}/users/authenticate`, requestOptions]
.then[handleResponse]
.then[user => {
// login thành công nếu có một token jwt trong response
if [user.token] {
// lưu dữ liệu user và token jwt vào local storage để giữ user được log in trong page
localStorage.setItem['user', JSON.stringify[user]];
}
return user;
}];
}
function logout[] {
// xoá user từ local storage để log out
localStorage.removeItem['user'];
}
function register[user] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/register`, requestOptions].then[handleResponse];
}
function getAll[] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users`, requestOptions].then[handleResponse];
}
function getById[id] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function update[user] {
const requestOptions = {
method: 'PUT',
headers: { ...authHeader[], 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/${user.id}`, requestOptions].then[handleResponse];
}
function _delete[id] {
const requestOptions = {
method: 'DELETE',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function handleResponse[response] {
return response.text[].then[text => {
const data = text && JSON.parse[text];
if [!response.ok] {
if [response.status === 401] {
// tự động logout nếu response 401 được trả về từ api
logout[];
location.reload[true];
}
const error = [data && data.message] || response.statusText;
return Promise.reject[error];
}
return data;
}];
}
1export * from './user.service';
Thư mục lưu trữ
Con đường. /src/cửa hàng
Vuex store chứa tất cả các module vuex và mọi thứ liên quan đến vuex store, nếu bạn chưa biết nhiều về vuex thì có thể tham khảo tại đây
Vuex quản lý tập tin trạng thái trong cửa hàng, nó có thể được truy cập từ bất kỳ thành phần nào, đột biến được cam kết để cập nhật các phần của trạng thái và hành động được gửi để thực hiện các chức năng phức tạp, có thể bao gồm các phần
Mô-đun tài khoản Vuex
Con đường. /src/cửa hàng/mô-đun/tài khoản. js
Mô-đun tài khoản Vuex được sử dụng để thao tác với phần tài khoản cho trạng thái trong cửa hàng. Nó chứa các hành động để đăng ký người dùng mới, đăng nhập và đăng xuất, và chứa các đột biến cho mỗi sự thay đổi trạng thái với mỗi tài khoản hành động
Trạng thái được khởi tạo cho người dùng được gán bằng giá trị người dùng đã được lưu trong bộ nhớ cục bộ, bao gồm giá trị xác định người dùng đã đăng nhập khi trình duyệt tải xuống hoặc giữa các phiên bản khác nhau của trình duyệt
import { userService } from '../../services';
import { router } from '../../helpers';
const user = JSON.parse[localStorage.getItem['user']];
const state = user
? { status: { loggedIn: true }, user }
: { status: {}, user: null };
const actions = {
login[{ dispatch, commit }, { username, password }] {
commit['loginRequest', { username }];
userService.login[username, password]
.then[
user => {
commit['loginSuccess', user];
router.push['/'];
},
error => {
commit['loginFailure', error];
dispatch['alert/error', error, { root: true }];
}
];
},
logout[{ commit }] {
userService.logout[];
commit['logout'];
},
register[{ dispatch, commit }, user] {
commit['registerRequest', user];
userService.register[user]
.then[
user => {
commit['registerSuccess', user];
router.push['/login'];
setTimeout[[] => {
// hiển thị message thành công sau redirect sang trang
dispatch['alert/success', 'Registration successful', { root: true }];
}]
},
error => {
commit['registerFailure', error];
dispatch['alert/error', error, { root: true }];
}
];
}
};
const mutations = {
loginRequest[state, user] {
state.status = { loggingIn: true };
state.user = user;
},
loginSuccess[state, user] {
state.status = { loggedIn: true };
state.user = user;
},
loginFailure[state] {
state.status = {};
state.user = null;
},
logout[state] {
state.status = {};
state.user = null;
},
registerRequest[state, user] {
state.status = { registering: true };
},
registerSuccess[state, user] {
state.status = {};
},
registerFailure[state, error] {
state.status = {};
}
};
export const account = {
namespaced: true,
state,
actions,
mutations
};
Mô-đun cảnh báo Vuex
Con đường. /src/store/mô-đun/cảnh báo. js
Mô-đun cảnh báo Vuex được sử dụng để xử lý phần cảnh báo cho trạng thái trong cửa hàng. Nó bao gồm các hành động và đột biến để cài đặt cảnh báo thông báo thành công hay lỗi, và cả việc xóa cảnh báo
Trong mô-đun này, mỗi cảnh báo hành động chỉ thực hiện một đột biến, vì vậy nó sẽ có thể thực hiện đột biến trực tiếp từ thành phần vue
________số 8Đường dẫn chỉ mục mô-đun. /src/cửa hàng/mô-đun/chỉ mục. js
import Vue from 'vue';
import Vuex from 'vuex';
import { alert } from './modules/alert';
import { account } from './modules/account';
Vue.use[Vuex];
export const store = new Vuex.Store[{
modules: {
alert,
account
}
}];
Cửa hàng Vuex
Con đường. /src/cửa hàng/chỉ mục. js
import Vue from 'vue';
import Router from 'vue-router';
import HomePage from '../components/HomePage'
import LoginPage from '../components/LoginPage'
import RegisterPage from '../components/RegisterPage'
Vue.use[Router];
export const router = new Router[{
mode: 'history',
routes: [
{ path: '/', component: HomePage },
{ path: '/login', component: LoginPage },
{ path: '/register', component: RegisterPage },
// nếu không sẽ chuyển đến trang home
{ path: '*', redirect: '/' }
]
}];
router.beforeEach[[to, from, next] => {
// chuyển đến trang login nếu chưa được login
const publicPages = ['/login', '/register'];
const authRequired = !publicPages.includes[to.path];
const loggedIn = localStorage.getItem['user'];
if [authRequired && !loggedIn] {
return next['/login'];
}
next[];
}]
0Thành phần ứng dụng Vue
Con đường. /src/Ứng dụng. vue
Thành phần ứng dụng là thành phần gốc cho vue, nó chứa mã html, định tuyến và thông báo cảnh báo cho ứng dụng
import Vue from 'vue';
import Router from 'vue-router';
import HomePage from '../components/HomePage'
import LoginPage from '../components/LoginPage'
import RegisterPage from '../components/RegisterPage'
Vue.use[Router];
export const router = new Router[{
mode: 'history',
routes: [
{ path: '/', component: HomePage },
{ path: '/login', component: LoginPage },
{ path: '/register', component: RegisterPage },
// nếu không sẽ chuyển đến trang home
{ path: '*', redirect: '/' }
]
}];
router.beforeEach[[to, from, next] => {
// chuyển đến trang login nếu chưa được login
const publicPages = ['/login', '/register'];
const authRequired = !publicPages.includes[to.path];
const loggedIn = localStorage.getItem['user'];
if [authRequired && !loggedIn] {
return next['/login'];
}
next[];
}]
1Thành phần thư mục
Thành phần trang đăng nhập Vue
Con đường. /src/thành phần/tài khoản/Trang đăng nhập. vue
Thành phần đăng nhập kết xuất form đăng nhập với tên người dùng và mật khẩu. Nó cũng hiển thị thông báo xác thực cho các trường không hợp lệ khi người dùng cố gắng gửi biểu mẫu. Nếu biểu mẫu hợp lệ, khi gửi sẽ gọi
import config from 'config';
import { authHeader } from '../helpers';
export const userService = {
login,
logout,
register,
getAll,
getById,
update,
delete: _delete
};
function login[username, password] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[{ username, password }]
};
return fetch[`${config.apiUrl}/users/authenticate`, requestOptions]
.then[handleResponse]
.then[user => {
// login thành công nếu có một token jwt trong response
if [user.token] {
// lưu dữ liệu user và token jwt vào local storage để giữ user được log in trong page
localStorage.setItem['user', JSON.stringify[user]];
}
return user;
}];
}
function logout[] {
// xoá user từ local storage để log out
localStorage.removeItem['user'];
}
function register[user] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/register`, requestOptions].then[handleResponse];
}
function getAll[] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users`, requestOptions].then[handleResponse];
}
function getById[id] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function update[user] {
const requestOptions = {
method: 'PUT',
headers: { ...authHeader[], 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/${user.id}`, requestOptions].then[handleResponse];
}
function _delete[id] {
const requestOptions = {
method: 'DELETE',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function handleResponse[response] {
return response.text[].then[text => {
const data = text && JSON.parse[text];
if [!response.ok] {
if [response.status === 401] {
// tự động logout nếu response 401 được trả về từ api
logout[];
location.reload[true];
}
const error = [data && data.message] || response.statusText;
return Promise.reject[error];
}
return data;
}];
}
2 được ánh xạ tới hành động import config from 'config';
import { authHeader } from '../helpers';
export const userService = {
login,
logout,
register,
getAll,
getById,
update,
delete: _delete
};
function login[username, password] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[{ username, password }]
};
return fetch[`${config.apiUrl}/users/authenticate`, requestOptions]
.then[handleResponse]
.then[user => {
// login thành công nếu có một token jwt trong response
if [user.token] {
// lưu dữ liệu user và token jwt vào local storage để giữ user được log in trong page
localStorage.setItem['user', JSON.stringify[user]];
}
return user;
}];
}
function logout[] {
// xoá user từ local storage để log out
localStorage.removeItem['user'];
}
function register[user] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/register`, requestOptions].then[handleResponse];
}
function getAll[] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users`, requestOptions].then[handleResponse];
}
function getById[id] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function update[user] {
const requestOptions = {
method: 'PUT',
headers: { ...authHeader[], 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/${user.id}`, requestOptions].then[handleResponse];
}
function _delete[id] {
const requestOptions = {
method: 'DELETE',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function handleResponse[response] {
return response.text[].then[text => {
const data = text && JSON.parse[text];
if [!response.ok] {
if [response.status === 401] {
// tự động logout nếu response 401 được trả về từ api
logout[];
location.reload[true];
}
const error = [data && data.message] || response.statusText;
return Promise.reject[error];
}
return data;
}];
}
3Trong hàm tạo[], hành động
import config from 'config';
import { authHeader } from '../helpers';
export const userService = {
login,
logout,
register,
getAll,
getById,
update,
delete: _delete
};
function login[username, password] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[{ username, password }]
};
return fetch[`${config.apiUrl}/users/authenticate`, requestOptions]
.then[handleResponse]
.then[user => {
// login thành công nếu có một token jwt trong response
if [user.token] {
// lưu dữ liệu user và token jwt vào local storage để giữ user được log in trong page
localStorage.setItem['user', JSON.stringify[user]];
}
return user;
}];
}
function logout[] {
// xoá user từ local storage để log out
localStorage.removeItem['user'];
}
function register[user] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/register`, requestOptions].then[handleResponse];
}
function getAll[] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users`, requestOptions].then[handleResponse];
}
function getById[id] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function update[user] {
const requestOptions = {
method: 'PUT',
headers: { ...authHeader[], 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/${user.id}`, requestOptions].then[handleResponse];
}
function _delete[id] {
const requestOptions = {
method: 'DELETE',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function handleResponse[response] {
return response.text[].then[text => {
const data = text && JSON.parse[text];
if [!response.ok] {
if [response.status === 401] {
// tự động logout nếu response 401 được trả về từ api
logout[];
location.reload[true];
}
const error = [data && data.message] || response.statusText;
return Promise.reject[error];
}
return data;
}];
}
4 được gửi thông qua hàm đăng xuất[], sẽ đăng xuất người dùng khi đã đăng nhập, nó sẽ chuyển sang trang đăng nhậpXác thực biểu mẫu được thực hiện thông qua thư viện VeeValidate
import Vue from 'vue';
import Router from 'vue-router';
import HomePage from '../components/HomePage'
import LoginPage from '../components/LoginPage'
import RegisterPage from '../components/RegisterPage'
Vue.use[Router];
export const router = new Router[{
mode: 'history',
routes: [
{ path: '/', component: HomePage },
{ path: '/login', component: LoginPage },
{ path: '/register', component: RegisterPage },
// nếu không sẽ chuyển đến trang home
{ path: '*', redirect: '/' }
]
}];
router.beforeEach[[to, from, next] => {
// chuyển đến trang login nếu chưa được login
const publicPages = ['/login', '/register'];
const authRequired = !publicPages.includes[to.path];
const loggedIn = localStorage.getItem['user'];
if [authRequired && !loggedIn] {
return next['/login'];
}
next[];
}]
0Thành phần đăng ký Vue
Con đường. /src/components/account/SignupPage. vue
Thành phần đăng ký sẽ hiển thị một biểu mẫu đăng ký đơn giản với tên, họ, tên người dùng và mật khẩu. Nó cũng hiển thị thông báo xác thực cho các trường không hợp lệ khi người dùng gửi biểu mẫu. Nếu biểu mẫu hợp lệ, khi gửi sẽ gọi hành động
import config from 'config';
import { authHeader } from '../helpers';
export const userService = {
login,
logout,
register,
getAll,
getById,
update,
delete: _delete
};
function login[username, password] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[{ username, password }]
};
return fetch[`${config.apiUrl}/users/authenticate`, requestOptions]
.then[handleResponse]
.then[user => {
// login thành công nếu có một token jwt trong response
if [user.token] {
// lưu dữ liệu user và token jwt vào local storage để giữ user được log in trong page
localStorage.setItem['user', JSON.stringify[user]];
}
return user;
}];
}
function logout[] {
// xoá user từ local storage để log out
localStorage.removeItem['user'];
}
function register[user] {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/register`, requestOptions].then[handleResponse];
}
function getAll[] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users`, requestOptions].then[handleResponse];
}
function getById[id] {
const requestOptions = {
method: 'GET',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function update[user] {
const requestOptions = {
method: 'PUT',
headers: { ...authHeader[], 'Content-Type': 'application/json' },
body: JSON.stringify[user]
};
return fetch[`${config.apiUrl}/users/${user.id}`, requestOptions].then[handleResponse];
}
function _delete[id] {
const requestOptions = {
method: 'DELETE',
headers: authHeader[]
};
return fetch[`${config.apiUrl}/users/${id}`, requestOptions].then[handleResponse];
}
function handleResponse[response] {
return response.text[].then[text => {
const data = text && JSON.parse[text];
if [!response.ok] {
if [response.status === 401] {
// tự động logout nếu response 401 được trả về từ api
logout[];
location.reload[true];
}
const error = [data && data.message] || response.statusText;
return Promise.reject[error];
}
return data;
}];
}
5 để gửi dữ liệu từ biểu mẫu