1. Go to this page and download the library: Download sun-asterisk/php-auth library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sun-asterisk / php-auth example snippets
public function register(Request $request)
{
$rules = [];
$fields = $request->only(['username', 'password', 'email']);
$result = $this->service->register($fields, $rules, function ($entity) {
return $entity->only(['id', 'email', 'username']);
});
return response()->json($result);
}
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$fields = $request->only(['username', 'password', 'email']);
$fields['name'] = $fields['username'];
$this->service->register($fields, [], function ($entity) {
//
});
return redirect()->intended('home');
}
$this->service->register($fields, [], function ($entity) {
//
}, true);
# App\Http\Controllers\AuthController
public function postForgotPassword(Request $request)
{
$email = $request->email;
$status = $this->service->postForgotPassword($email, function ($token, $user) {
// Use send mail from framework
sendEmail($user, $token);
});
return response()->json([
'ok' => $status,
'type' => 'forgotPassword',
]);
}
public function confirm(Request $request)
{
$token = $request->token;
$status = $this->service->verifyToken($token);
return response()->json([
'ok' => $status,
]);
}
# SunAsterisk\Auth\SunServiceProvider
/**
* Extend Laravel's Auth.
*
* @return void
*/
protected function extendAuthGuard(): void
{
$this->app['auth']->extend('sun', function ($app, $name, array $config) {
$storage = $app->make(Providers\Storage::class);
$blackList = new SunBlacklist($storage);
$jwt = new SunJWT($blackList, $app->config->get('sun-asterisk.auth'));
$tokenMapper = new SunTokenMapper($storage);
$guard = new SunGuard(
$jwt,
$app['auth']->createUserProvider($config['provider']),
$app['request'],
$tokenMapper
);
app()->refresh('request', $guard, 'setRequest');
return $guard;
});
}
# SunAsterisk\Auth\SunGuard
/**
* Logout the user, thus invalidating the token.
*
* @return void
*/
public function logout()
{
try {
$token = $this->request->bearerToken();
$rawToken = $this->jwt->decode($token);
$refreshToken = $this->tokenMapper->pullRefreshToken($rawToken['jti']);
$this->jwt->invalidate($token);
if ($refreshToken) {
$this->jwt->invalidate($refreshToken, true);
}
} catch (\Exception $e) {
throw new Exceptions\JWTException($e->getMessage());
}
}
# SunAsterisk\Auth\SunJWT
public function invalidate(string $token, bool $isRefresh = false): bool
{
if (! $this->blackList) {
throw new Exceptions\JWTException('You must have the blacklist enabled to invalidate a token.');
}
$payload = $this->decode($token, $isRefresh, false);
return $this->blackList->add($payload);
}
/**
* [register]
* @param array $fields [The user's attributes for register.]
* @param array $rules [The rules for register validate.]
* @param callable|null $callback [The callback function has the entity model.]
* @return [array]
*/
public function register(array $params = [], array $rules = [], callable $callback = null): array;
# SunAsterisk\Auth\Services\AuthJWTService;
public function verifyToken(string $token, callable $callback = null): bool
{
...
$objStr = Crypt::decryptString($token);
$obj = json_decode($objStr, true);
...
$diffSeconds = Carbon::now()->diffInSeconds(Carbon::createFromTimestamp($obj['created_at']));
if ($diffSeconds >= $this->config['token_expires'] * 60) {
throw new AuthException('Token is invalid!');
}
}
# SunAsterisk\Auth\Services\AuthJWTService;
public function changePassword(array $params = [], ?int $userId = null, callable $callback = null): bool
{
...
$user = null;
$attr = [];
// For usecase forgot password
if (isset($params['token'])) {
$this->verifyToken($params['token'], function ($entity) use (&$user) {
$user = $entity;
});
}
...
if ($user) {
$attr[$this->passwd()] = Hash::make($params[$this->passwd()]);
...
$this->repository->updateById($user->id, $attr);
}
...
}
/**
* [refresh]
* @param string $refreshToken [refresh_token for user get access_token]
* @param callable|null $callback [The callback function has the entity model.]
* @return [array]
*/
public function refresh(?string $refreshToken, callable $callback = null): array;
# SunAsterisk\Auth\Services\AuthJWTService;
public function refresh(?string $refreshToken, callable $callback = null): array
{
...
$payload = $this->jwt->decode($refreshToken ?: '', true);
}
# SunAsterisk\Auth\Services\AuthJWTService;
public function refresh(?string $refreshToken, callable $callback = null): array
{
...
if (Carbon::createFromTimestamp($payload['exp'])->lte(Carbon::now())) {
throw new InvalidArgumentException('The RefreshToken is invalid.');
}
}
# SunAsterisk\Auth\Services\AuthJWTService;
public function refresh(?string $refreshToken, callable $callback = null): array
{
...
$item = $this->repository->findById($sub?->id);
if (!$item) {
throw new InvalidArgumentException('The RefreshToken is invalid.');
}
}
# SunAsterisk\Auth\Services\AuthJWTService;
public function revoke(array $keys = []): bool
{
try {
return $this->jwt->revoke($keys);
} catch (\Exception $e) {
throw new Exceptions\JWTException('Revoke token is wrong.');
}
}
/**
* [socialSignIn]
* @param string $provider [The Provider should received from https://socialiteproviders.com/about/]
* @return [Illuminate\Http\RedirectResponse]
*/
public function socialSignIn(?string $provider): RedirectResponse;
/**
* [socialCallback]
* @param string $provider [The Provider should received from https://socialiteproviders.com/about/]
* @return [stdClass]
*/
public function socialCallback(?string $provider): stdClass;
# SunAsterisk\Auth\Services\AuthSocialService
/**
* [socialSignIn]
* @param string $provider [The Provider should received from https://socialiteproviders.com/about/]
* @return [Illuminate\Http\RedirectResponse]
*/
public function socialSignIn(?string $provider): RedirectResponse
{
try {
return Socialite::driver($provider)->redirect();
} catch (\Exception $e) {
throw new InvalidArgumentException('provider is invalid!');
# SunAsterisk\Auth\Services\AuthSocialService
/**
* [socialCallback]
* @param string $provider [The Provider should received from https://socialiteproviders.com/about/]
* @return [stdClass]
*/
public function socialCallback(?string $provider): stdClass
{
try {
return Socialite::driver($provider)->user();
} catch (\Exception $e) {
throw new InvalidArgumentException('provider is invalid!');
}
}