Commit 7b7a03f1 authored by Damis Bachtiar's avatar Damis Bachtiar

Initial commit

parents
Pipeline #8 failed with stages
{
"presets": [
"env",
"stage-0"
]
}
\ No newline at end of file
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
typings
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# Dist directory
dist
\ No newline at end of file
MIT License
Copyright (c) 2018 Jason Watmore
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# vue-vuex-registration-login-example
Vue + Vuex - User Registration and Login Tutorial & Example
To see a demo and further details go to http://jasonwatmore.com/post/2018/07/14/vue-vuex-user-registration-and-login-tutorial-example
\ No newline at end of file
This diff is collapsed.
{
"name": "vue-vuex-registration-login-example",
"version": "1.0.0",
"repository": {
"type": "git",
"url": "https://github.com/cornflourblue/vue-vuex-registration-login-example.git"
},
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open",
"build": "webpack --mode production"
},
"dependencies": {
"axios": "^0.19.2",
"vee-validate": "^2.2.8",
"vue": "^2.6.10",
"vue-router": "^3.1.3",
"vuex": "^3.1.2"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-vue": "^2.0.2",
"css-loader": "^3.3.2",
"html-webpack-plugin": "^3.2.0",
"path": "^0.12.7",
"vue-loader": "^14.2.3",
"vue-template-compiler": "^2.6.10",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
}
}
export function authHeader() {
// return authorization header with jwt token
let user = JSON.parse(localStorage.getItem('user'));
if (user && user.token) {
return { 'Authorization': 'Bearer ' + user.token };
} else {
return {};
}
}
\ No newline at end of file
export * from './router';
export * from './auth-header';
\ No newline at end of file
import Vue from 'vue';
import Router from 'vue-router';
import HomePage from '../components/home/HomePage'
import LoginPage from '../components/login/LoginPage'
import RegisterPage from '../components/register/RegisterPage'
Vue.use(Router);
export const router = new Router({
mode: 'history',
routes: [
{ path: '/', component: HomePage },
{ path: '/login', component: LoginPage },
{ path: '/register', component: RegisterPage },
// otherwise redirect to home
{ path: '*', redirect: '/' }
]
});
router.beforeEach((to, from, next) => {
// redirect to login page if not logged in and trying to access a restricted page
const publicPages = ['/login', '/register'];
const authRequired = !publicPages.includes(to.path);
const loggedIn = localStorage.getItem('user');
if (authRequired && !loggedIn) {
return next('/login');
}
next();
})
\ No newline at end of file
export * from './user.service';
import config from 'config'
import { authHeader } from '../_helpers'
const axios = require('axios')
axios.defaults.baseURL = 'https://reqres.in/api/'
const headers = {
'Content-Type': 'application/json'
}
export const userService = {
login,
logout,
register,
getAll,
};
function login(email, password) {
let data = JSON.stringify({
email,password
})
return axios.post('/login', data, {headers})
.then(function(response) {
const user = {
email,
'firstName': 'Test',
'lastName': 'User',
'token' : response.token
}
localStorage.setItem('user',JSON.stringify(user))
return response.data
})
}
function logout() {
// remove user from local storage to log user out
localStorage.removeItem('user');
}
function register(user) {
let data = JSON.stringify({
'email': user.email,
'password' : user.password
})
return axios.post('/register', data, {headers})
.then(function(response) {
const user = {
email,
'firstName': 'Test',
'lastName': 'User',
'token' : response.token
}
localStorage.setItem('user',JSON.stringify(user))
return response.data
})
}
function getAll(params) {
return axios.get('users',{
params
})
.then(function(response) {
return response.data
})
.catch(function(error){
return handleError(error);
})
}
function handleError(error){
if(!error.response){
error.message = 'Tidak terhubung ke internet'
return error
}else{
return error.response
}
}
\ No newline at end of file
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 }, { email, password }) {
commit('loginRequest', { email });
userService.login(email, 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(() => {
// display success message after route change completes
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
};
\ No newline at end of file
const state = {
type: null,
message: null
};
const actions = {
success({ commit }, message) {
commit('success', message);
},
error({ commit }, message) {
commit('error', message);
},
clear({ commit }, message) {
commit('success', message);
}
};
const mutations = {
success(state, message) {
state.type = 'alert-success';
state.message = message;
},
error(state, message) {
state.type = 'alert-danger';
state.message = message;
},
clear(state) {
state.type = null;
state.message = null;
}
};
export const alert = {
namespaced: true,
state,
actions,
mutations
};
import Vue from 'vue';
import Vuex from 'vuex';
import { alert } from './alert.module';
import { account } from './account.module';
import { users } from './users.module';
Vue.use(Vuex);
export const store = new Vuex.Store({
modules: {
alert,
account,
users
}
});
import { userService } from '../_services';
const state = {
all: {
loading: false,
list:null,
create:null,
update:null,
delete:null,
error:null
}
};
const actions = {
getAll({ commit }) {
commit('sendRequest');
userService.getAll()
.then(
users => commit('getAllSuccess', users),
error => commit('getAllFailure', error)
);
commit('endRequest')
},
delete({ commit }, id) {
commit('deleteRequest', id);
userService.delete(id)
.then(
user => commit('deleteSuccess', id),
error => commit('deleteFailure', { id, error: error.toString() })
);
}
};
const mutations = {
sendRequest(state) {
state.all.loading = true
},
endRequest(state) {
state.all.loading = false
},
getAllSuccess(state, users) {
state.all.list = users
},
getAllFailure(state, error) {
state.all.error = error;
},
deleteRequest(state, id) {
// add 'deleting:true' property to user being deleted
state.all.items = state.all.items.map(user =>
user.id === id
? { ...user, deleting: true }
: user
)
},
deleteSuccess(state, id) {
// remove deleted user from state
state.all.items = state.all.items.filter(user => user.id !== id)
},
deleteFailure(state, { id, error }) {
// remove 'deleting:true' property and add 'deleteError:[error]' property to user
state.all.items = state.items.map(user => {
if (user.id === id) {
// make copy of user without 'deleting:true' property
const { deleting, ...userCopy } = user;
// return copy of user with 'deleteError:[error]' property
return { ...userCopy, deleteError: error };
}
return user;
})
}
};
export const users = {
namespaced: true,
state,
actions,
mutations
};
<template>
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-sm-6 offset-sm-3">
<div v-if="alert.message" :class="`alert ${alert.type}`">{{alert.message}}</div>
<router-view></router-view>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'app',
computed: {
...mapState({
alert: state => state.alert
})
},
methods: {
...mapActions({
clearAlert: 'alert/clear'
})
},
watch: {
$route (to, from){
// clear alert on location change
this.clearAlert();
}
}
};
</script>
\ No newline at end of file
<template>
<div>
<h1>Hi {{account.user.firstName}}!</h1>
<p>You're logged in with Vue + Vuex & JWT!!</p>
<h3>Users from secure api end point:</h3>
<em v-if="users.loading">Loading users...</em>
<span v-if="users.error" class="text-danger">ERROR: {{users.error}}</span>
<ul v-if="users.all.list">
<li v-for="user in users.all.list.data" :key="user.id">
{{user.first_name}}
<span v-if="user.deleting"><em> - Deleting...</em></span>
<span v-else-if="user.deleteError" class="text-danger"> - ERROR: {{user.deleteError}}</span>
<span v-else> - <a @click="deleteUser(user.id)" class="text-danger">Delete</a></span>
</li>
</ul>
<p>
<router-link to="/login">Logout</router-link>
</p>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: {
...mapState([
"account",["all"],
"users",["all"]
]),
},
created () {
this.getAllUsers();
},
methods: {
...mapActions('users', {
getAllUsers: 'getAll',
deleteUser: 'delete'
})
}
};
</script>
\ No newline at end of file
<template>
<div>
<h2>Login</h2>
<div class="form-group">
<label for="email">email</label>
<input type="text" v-model="email" name="email" class="form-control" :class="{ 'is-invalid': submitted && !email }" />
<div v-show="submitted && !email" class="invalid-feedback">Email is required</div>
</div>
<div class="form-group">
<label htmlFor="password">Password</label>
<input type="password" v-model="password" name="password" class="form-control" :class="{ 'is-invalid': submitted && !password }" />
<div v-show="submitted && !password" class="invalid-feedback">Password is required</div>
</div>
<div class="form-group">
<button class="btn btn-primary" :disabled="status.loggingIn" @click="callLogin()">Login</button>
<img v-show="status.loggingIn" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
<router-link to="/register" class="btn btn-link">Register</router-link>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
data () {
return {
email: '',
password: '',
submitted: false
}
},
computed: {
...mapState('account', ['status'])
},
created () {
// reset login status
this.logout();
},
methods: {
...mapActions('account', ['login', 'logout']),
callLogin(){
this.submitted = true;
const { email, password } = this;
if (email && password) {
this.login({ email, password })
}
}
}
};
</script>
\ No newline at end of file
<template>
<div>
<h2>Register</h2>
<div class="form-group">
<label for="email">Email</label>
<input type="text" v-model="user.email" v-validate="'required'" name="email" class="form-control" :class="{ 'is-invalid': submitted && errors.has('email') }" />
<div v-if="submitted && errors.has('email')" class="invalid-feedback">{{ errors.first('email') }}</div>
</div>
<div class="form-group">
<label htmlFor="password">Password</label>
<input type="password" v-model="user.password" v-validate="{ required: true, min: 6 }" name="password" class="form-control" :class="{ 'is-invalid': submitted && errors.has('password') }" />
<div v-if="submitted && errors.has('password')" class="invalid-feedback">{{ errors.first('password') }}</div>
</div>
<div class="form-group">
<button class="btn btn-primary" :disabled="status.registering" @click="callRegister()">Register</button>
<img v-show="status.registering" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
<router-link to="/login" class="btn btn-link">Cancel</router-link>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
data () {
return {
user: {
email: '',
password: ''
},
submitted: false
}
},
computed: {
...mapState('account', ['status'])
},
methods: {
...mapActions('account', ['register']),
callRegister(){
const {user} = this
this.register({user})
}
}
};
</script>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue + Vuex - User Registration and Login Example & Tutorial</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<style>
a { cursor: pointer; }
</style>
</head>
<body>
<div id="app"></div>
<!-- credits -->
<div class="text-center">
<p>
<a href="http://jasonwatmore.com/post/2018/07/14/vue-vuex-user-registration-and-login-tutorial-example" target="_top">Vue + Vuex - User Registration and Login Tutorial & Example</a>
</p>
<p>
<a href="http://jasonwatmore.com" target="_top">JasonWatmore.com</a>
</p>
</div>
</body>
</html>
\ No newline at end of file
import Vue from 'vue';
import VeeValidate from 'vee-validate';
import { store } from './_store';
import { router } from './_helpers';
import App from './app/App';
Vue.use(VeeValidate);
new Vue({
el: '#app',
router,
store,
render: h => h(App)
});
\ No newline at end of file
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
resolve: {
extensions: ['.js', '.vue']
},
module: {
rules: [
{
test: /\.vue?$/,
exclude: /(node_modules)/,
use: 'vue-loader'
},
{
test: /\.js?$/,
exclude: /(node_modules)/,
use: 'babel-loader'
}
]
},
plugins: [new HtmlWebpackPlugin({
template: './src/index.html'
})],
devServer: {
historyApiFallback: true
},
externals: {
// global app config object
config: JSON.stringify({
apiUrl: 'https://reqres.in/api/'