Skip to content

Commit 661ae70

Browse files
author
Jovert Lota Palonpon
committed
[Authentication] Updated how persistent data is stored
1 parent 2422111 commit 661ae70

File tree

10 files changed

+202
-75136
lines changed

10 files changed

+202
-75136
lines changed

app/Http/Controllers/Api/Auth/SessionsController.php

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public function identify(Request $request) : JsonResponse
3535
}
3636

3737
/**
38-
* Authenticate the user and then give it's userId.
38+
* Authenticate the user and give the token data.
3939
*
4040
* @param Illuminate\Http\Request
4141
*
@@ -49,7 +49,7 @@ public function signin(Request $request) : JsonResponse
4949
]);
5050

5151
if ($token = $this->attempt($request)) {
52-
return $this->respondWithUserId($token);
52+
return $this->respondWithToken($token);
5353
}
5454

5555
throw ValidationException::withMessages([
@@ -59,20 +59,6 @@ public function signin(Request $request) : JsonResponse
5959
return response()->json(['error' => 'Unauthorized'], 401);
6060
}
6161

62-
/**
63-
* Get the auth token.
64-
*
65-
* @param Illuminate\Http\Request
66-
*
67-
* @return \Illuminate\Http\JsonResponse
68-
*/
69-
public function token(Request $request) : JsonResponse
70-
{
71-
return response()->json(
72-
optional(User::find($request->input('uid')))->auth_token
73-
);
74-
}
75-
7662
/**
7763
* Try to authenticate the user.
7864
*
@@ -105,17 +91,21 @@ protected function identifier(Request $request) : string
10591
/**
10692
* Get the authenticated user's Id.
10793
*
108-
* @param string $token
94+
* @param string $authToken
10995
*
11096
* @return Illuminate\Http\JsonResponse
11197
*/
112-
protected function respondWithUserId($token) : JsonResponse
98+
protected function respondWithToken($authToken) : JsonResponse
11399
{
114-
$user = JWTAuth::setToken($token)->toUser();
100+
$user = JWTAuth::setToken($authToken)->toUser();
115101

116-
$this->saveAuthToken($token, $user);
102+
$this->saveAuthToken($authToken, $user);
117103

118-
return response()->json($user->id);
104+
return response()->json([
105+
'auth_token' => $authToken,
106+
'token_type' => 'bearer',
107+
'expires_in' => $this->guard()->factory()->getTTL() * 60
108+
]);
119109
}
120110

121111
/**
@@ -151,7 +141,7 @@ public function user() : JsonResponse
151141
*/
152142
public function refresh()
153143
{
154-
return $this->respondWithUserId($this->guard()->refresh());
144+
return $this->respondWithToken($this->guard()->refresh());
155145
}
156146

157147
/**
@@ -171,7 +161,7 @@ public function signout() : JsonResponse
171161
*
172162
* @return \Illuminate\Contracts\Auth\Guard
173163
*/
174-
public function guard() : Guard
164+
protected function guard() : Guard
175165
{
176166
return Auth::guard('api');
177167
}

public/assets.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
{
2-
"js/backoffice.js": "js/backoffice.bundle.d1d987f51245810acc04.js",
3-
"js/vendor.js": "js/vendor.bundle.60bab7ed0c4b898e6cd4.js"
2+
"js/backoffice.js": "js/backoffice.bundle.55554000828c6880bf25.js",
3+
"js/vendor.js": "js/vendor.bundle.86f41802dd6246f92186.js"
44
}

public/js/backoffice.bundle.55554000828c6880bf25.js

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

public/js/backoffice.bundle.d1d987f51245810acc04.js

Lines changed: 0 additions & 809 deletions
This file was deleted.

public/js/vendor.bundle.60bab7ed0c4b898e6cd4.js

Lines changed: 0 additions & 74270 deletions
This file was deleted.

public/js/vendor.bundle.86f41802dd6246f92186.js

Lines changed: 134 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

public/service-worker.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

resources/js/Backoffice.js

Lines changed: 45 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,33 @@ import { Loading } from './views';
1010
class Backoffice extends Component {
1111
state = {
1212
loading: true,
13-
authToken: null,
1413
authenticated: false,
15-
username: '',
14+
auth: {},
1615
user: {},
16+
username: '',
17+
};
18+
19+
/**
20+
* Authenticate the user.
21+
*
22+
* @param {string} tokenString
23+
*
24+
* @return {undefined}
25+
*/
26+
authenticate = async (tokenString = null) => {
27+
const auth = JSON.parse(tokenString);
28+
29+
// We will set a default Authorization header, this will
30+
// eliminate the need to include the Authorization header
31+
// for almost every AJAX requests.
32+
window.axios.defaults.headers.common['Authorization'] = `Bearer ${
33+
auth.auth_token
34+
}`;
35+
36+
// Store it locally for the authentication data to persist.
37+
window.localStorage.setItem('auth', tokenString);
38+
39+
await this.fetchAuthUser();
1740
};
1841

1942
/**
@@ -28,8 +51,8 @@ class Backoffice extends Component {
2851
const response = await axios.post('/api/auth/signout');
2952

3053
if (response.status === 200) {
31-
// remove uid stored in localStorage.
32-
await localStorage.removeItem('uid');
54+
// remove auth data stored in localStorage.
55+
await localStorage.removeItem('auth');
3356

3457
this.setState({
3558
loading: false,
@@ -65,27 +88,21 @@ class Backoffice extends Component {
6588
};
6689

6790
/**
68-
* Fetch the Authentication Token.
91+
* Get the Authentication Data from the persistent storage.
6992
*
70-
* @return {undefined}
93+
* @return {object}
7194
*/
72-
fetchAuthToken = async () => {
73-
try {
74-
const response = await axios.post('/api/auth/token', {
75-
uid: window.localStorage.getItem('uid'),
76-
});
95+
getAuthData = async () => {
96+
const authString = await window.localStorage.getItem('auth');
97+
const auth = JSON.parse(authString);
7798

78-
if (response.status === 200) {
79-
// We will set a default Authorization header, this will
80-
// eliminate the need to include the Authorization header
81-
// for almost every AJAX requests.
82-
window.axios.defaults.headers.common[
83-
'Authorization'
84-
] = `Bearer ${response.data}`;
85-
86-
this.setState({ authToken: response.data });
87-
}
88-
} catch (error) {}
99+
if (!authString) {
100+
return {};
101+
}
102+
103+
this.setState({ auth });
104+
105+
return auth;
89106
};
90107

91108
/**
@@ -107,15 +124,17 @@ class Backoffice extends Component {
107124
};
108125

109126
async componentDidMount() {
110-
await this.fetchAuthToken();
127+
const auth = await this.getAuthData();
111128

112-
await this.fetchAuthUser();
129+
if (auth) {
130+
await this.authenticate(JSON.stringify(auth));
131+
}
113132

114133
this.setState({ loading: false });
115134
}
116135

117136
render() {
118-
const { classes, width } = this.props;
137+
const { width } = this.props;
119138
const { loading } = this.state;
120139

121140
return (
@@ -132,6 +151,7 @@ class Backoffice extends Component {
132151
width,
133152
environment: 'backoffice',
134153
routes: ROUTES,
154+
authenticate: this.authenticate,
135155
handleLock: this.handleLock,
136156
handleSignout: this.handleSignout,
137157
}}

resources/js/views/auth/SignIn.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ class SignIn extends Component {
116116
this.setState({ loading: true });
117117

118118
try {
119+
const { pageProps } = this.props;
119120
const { username } = this.state;
120121
const { password } = values;
121122

@@ -124,13 +125,13 @@ class SignIn extends Component {
124125
password,
125126
});
126127

127-
if (response.status === 200) {
128-
window.localStorage.setItem('uid', response.data);
128+
if (response.status !== 200) {
129+
return;
130+
}
129131

130-
this.setState({ loading: false });
132+
pageProps.authenticate(JSON.stringify(response.data));
131133

132-
window.location.reload();
133-
}
134+
this.setState({ loading: false });
134135
} catch (error) {
135136
if (!error.response) {
136137
throw new Error('Unknown error');

routes/api.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
Route::namespace('Auth')->name('auth.')->prefix('auth')->group(function () {
1616
Route::post('identify', 'SessionsController@identify')->name('identify');
1717
Route::post('signin', 'SessionsController@signin')->name('signin');
18-
Route::post('token', 'SessionsController@token')->name('token');
1918

2019
Route::middleware('auth:api')->group(function () {
2120
Route::post('signout', 'SessionsController@signout')->name('signout');

0 commit comments

Comments
 (0)