Skip to content

Commit 1e8b86e

Browse files
committed
Laravel Nuxt Cli Sanctum authentication Laravel part
0 parents  commit 1e8b86e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

83 files changed

+10291
-0
lines changed

.editorconfig

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
root = true
2+
3+
[*]
4+
charset = utf-8
5+
end_of_line = lf
6+
insert_final_newline = true
7+
indent_style = space
8+
indent_size = 4
9+
trim_trailing_whitespace = true
10+
11+
[*.md]
12+
trim_trailing_whitespace = false
13+
14+
[*.{yml,yaml}]
15+
indent_size = 2

.env.example

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
APP_NAME=Laravel
2+
APP_ENV=local
3+
APP_KEY=base64:XK6W/zLOJtinBw46z73My+Zp5Evd//QfQoetMsnR4FQ=
4+
APP_DEBUG=true
5+
APP_URL=http://localhost
6+
7+
LOG_CHANNEL=stack
8+
9+
DB_CONNECTION=mysql
10+
DB_HOST=127.0.0.1
11+
DB_PORT=3306
12+
DB_DATABASE=laravel
13+
DB_USERNAME=root
14+
DB_PASSWORD=
15+
16+
BROADCAST_DRIVER=log
17+
CACHE_DRIVER=file
18+
QUEUE_CONNECTION=sync
19+
SESSION_DRIVER=file
20+
SESSION_LIFETIME=120
21+
22+
REDIS_HOST=127.0.0.1
23+
REDIS_PASSWORD=null
24+
REDIS_PORT=6379
25+
26+
MAIL_MAILER=smtp
27+
MAIL_HOST=smtp.mailtrap.io
28+
MAIL_PORT=2525
29+
MAIL_USERNAME=null
30+
MAIL_PASSWORD=null
31+
MAIL_ENCRYPTION=null
32+
MAIL_FROM_ADDRESS=null
33+
MAIL_FROM_NAME="${APP_NAME}"
34+
35+
AWS_ACCESS_KEY_ID=
36+
AWS_SECRET_ACCESS_KEY=
37+
AWS_DEFAULT_REGION=us-east-1
38+
AWS_BUCKET=
39+
40+
PUSHER_APP_ID=
41+
PUSHER_APP_KEY=
42+
PUSHER_APP_SECRET=
43+
PUSHER_APP_CLUSTER=mt1
44+
45+
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
46+
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
47+
48+
# Laravel Domain
49+
SESSION_DOMAIN=localhost
50+
51+
# Nuxt Domain
52+
SANCTUM_STATEFUL_DOMAINS=localhost:3000

.gitattributes

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
* text=auto
2+
*.css linguist-vendored
3+
*.scss linguist-vendored
4+
*.js linguist-vendored
5+
CHANGELOG.md export-ignore

.gitignore

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/node_modules
2+
/public/hot
3+
/public/storage
4+
/storage/*.key
5+
/vendor
6+
.env
7+
.env.backup
8+
.phpunit.result.cache
9+
Homestead.json
10+
Homestead.yaml
11+
npm-debug.log
12+
yarn-error.log

.styleci.yml

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
php:
2+
preset: laravel
3+
disabled:
4+
- unused_use
5+
finder:
6+
not-name:
7+
- index.php
8+
- server.php
9+
js:
10+
finder:
11+
not-name:
12+
- webpack.mix.js
13+
css: true

README.md

+178
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
## Laravel & Nuxt CLI Authentication - Laravel Part
2+
3+
A. Install & setup Sanctum
4+
5+
1) composer require laravel/sanctum
6+
2 ) php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
7+
3 ) php artisan migrate
8+
4 ) EnsureFrontendRequestsAreStateful::class in Karnel.php
9+
10+
B. .env
11+
**Laravel Domain**
12+
SESSION_DOMAIN=localhost
13+
14+
**Nuxt Domain**
15+
SANCTUM_STATEFUL_DOMAINS=localhost:3000
16+
17+
C. routes/api.php
18+
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
19+
return $request->user();
20+
});
21+
// Login & Logout routes
22+
Route::post('/login', 'Auth\LoginController@login');
23+
Route::post('/logout', 'Auth\LoginController@logout');
24+
25+
D. config/cors.php - replace
26+
'paths' => ['api/*', 'sanctum/csrf-cookie'],
27+
into
28+
'paths' => ['api/*'],
29+
30+
E. App/Users.php
31+
use HasApiTokens
32+
33+
F. App/Http/Controllers/Auth/LoginController.php
34+
public function login(Request $request)
35+
{
36+
$request->validate([
37+
'email' => 'required',
38+
'password' => 'required'
39+
]);
40+
if (!Auth::attempt($request->only('email', 'password'))) {
41+
throw new AuthenticationException();
42+
}
43+
return $this->jsonResponse(true, auth()->user(), 200);
44+
}
45+
46+
public function logout()
47+
{
48+
if (auth()->check()) {
49+
Auth::logout();
50+
return $this->jsonResponse(true, 'Logged out successfully', 200);
51+
}
52+
return $this->jsonResponse(true, 'Something went wrong', 404);
53+
}
54+
55+
private function jsonResponse($success, $data, $status)
56+
{
57+
return response()->json([
58+
'success' => $success,
59+
'data' => $data,
60+
], $status);
61+
}
62+
63+
64+
## Nuxt / Vue cli
65+
A. login.vue
66+
1 ) import axios from 'axios'
67+
2 ) axios.defaults.withCredentials = true
68+
3 ) make an helper function - laravelCsrfCookies()
69+
every time before any function call this function and return true .
70+
71+
methods: {
72+
laravelCsrfCoockie() {
73+
axios.get(this.baseURL + 'sanctum/csrf-cookie').then((response) => {
74+
return true
75+
})
76+
},
77+
login() {
78+
this.laravelCsrfCoockie()
79+
axios
80+
.post(this.baseURL + 'api/login', {
81+
email: this.email,
82+
password: this.password,
83+
})
84+
.then((res) => {
85+
localStorage.setItem('me', JSON.stringify(res.data))
86+
this.loggedIn = localStorage.getItem('me')
87+
this.userName = JSON.parse(localStorage.getItem('me')).data.name
88+
console.log(this.loggedIn)
89+
})
90+
.catch((err) => {
91+
console.log(err)
92+
})
93+
},
94+
logout() {
95+
this.laravelCsrfCoockie()
96+
axios
97+
.post(this.baseURL + 'api/logout')
98+
.then((res) => {
99+
localStorage.removeItem('me')
100+
this.loggedIn = null
101+
this.userName = 'Guest User'
102+
console.log(this.loggedIn)
103+
})
104+
.catch((err) => {
105+
console.log(err)
106+
})
107+
},
108+
109+
110+
B. Demo Login.vue
111+
<template>
112+
<div>
113+
<button v-if="!loggedIn" @click="login">Login</button>
114+
<button v-else @click="logout">logout</button>
115+
<h1 v-if="userName">{{ userName }}</h1>
116+
</div>
117+
</template>
118+
<script>
119+
import axios from 'axios'
120+
axios.defaults.withCredentials = true
121+
122+
export default {
123+
data() {
124+
return {
125+
126+
password: 'password',
127+
baseURL: 'http://localhost:8000/',
128+
loggedIn: localStorage.getItem('me'),
129+
userName: localStorage.getItem('me')
130+
? JSON.parse(localStorage.getItem('me')).data.name
131+
: 'Guest User',
132+
}
133+
},
134+
mounted() {
135+
console.log(this.loggedIn)
136+
},
137+
methods: {
138+
laravelCsrfCoockie() {
139+
axios.get(this.baseURL + 'sanctum/csrf-cookie').then((response) => {
140+
return true
141+
})
142+
},
143+
login() {
144+
this.laravelCsrfCoockie()
145+
axios
146+
.post(this.baseURL + 'api/login', {
147+
email: this.email,
148+
password: this.password,
149+
})
150+
.then((res) => {
151+
localStorage.setItem('me', JSON.stringify(res.data))
152+
this.loggedIn = localStorage.getItem('me')
153+
this.userName = JSON.parse(localStorage.getItem('me')).data.name
154+
console.log(this.loggedIn)
155+
})
156+
.catch((err) => {
157+
console.log(err)
158+
})
159+
},
160+
logout() {
161+
this.laravelCsrfCoockie()
162+
axios
163+
.post(this.baseURL + 'api/logout')
164+
.then((res) => {
165+
localStorage.removeItem('me')
166+
this.loggedIn = null
167+
this.userName = 'Guest User'
168+
console.log(this.loggedIn)
169+
})
170+
.catch((err) => {
171+
console.log(err)
172+
})
173+
},
174+
},
175+
}
176+
</script>
177+
178+
**You can use this starter project for to remove the hasslement of Laravel & Sanctum/Vue Cli**

app/Console/Kernel.php

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
namespace App\Console;
4+
5+
use Illuminate\Console\Scheduling\Schedule;
6+
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
7+
8+
class Kernel extends ConsoleKernel
9+
{
10+
/**
11+
* The Artisan commands provided by your application.
12+
*
13+
* @var array
14+
*/
15+
protected $commands = [
16+
//
17+
];
18+
19+
/**
20+
* Define the application's command schedule.
21+
*
22+
* @param \Illuminate\Console\Scheduling\Schedule $schedule
23+
* @return void
24+
*/
25+
protected function schedule(Schedule $schedule)
26+
{
27+
// $schedule->command('inspire')->hourly();
28+
}
29+
30+
/**
31+
* Register the commands for the application.
32+
*
33+
* @return void
34+
*/
35+
protected function commands()
36+
{
37+
$this->load(__DIR__.'/Commands');
38+
39+
require base_path('routes/console.php');
40+
}
41+
}

app/Exceptions/Handler.php

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
namespace App\Exceptions;
4+
5+
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
6+
use Throwable;
7+
8+
class Handler extends ExceptionHandler
9+
{
10+
/**
11+
* A list of the exception types that are not reported.
12+
*
13+
* @var array
14+
*/
15+
protected $dontReport = [
16+
//
17+
];
18+
19+
/**
20+
* A list of the inputs that are never flashed for validation exceptions.
21+
*
22+
* @var array
23+
*/
24+
protected $dontFlash = [
25+
'password',
26+
'password_confirmation',
27+
];
28+
29+
/**
30+
* Report or log an exception.
31+
*
32+
* @param \Throwable $exception
33+
* @return void
34+
*
35+
* @throws \Exception
36+
*/
37+
public function report(Throwable $exception)
38+
{
39+
parent::report($exception);
40+
}
41+
42+
/**
43+
* Render an exception into an HTTP response.
44+
*
45+
* @param \Illuminate\Http\Request $request
46+
* @param \Throwable $exception
47+
* @return \Symfony\Component\HttpFoundation\Response
48+
*
49+
* @throws \Throwable
50+
*/
51+
public function render($request, Throwable $exception)
52+
{
53+
return parent::render($request, $exception);
54+
}
55+
}

0 commit comments

Comments
 (0)