code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
protected function formatUrl(string $url): string { $uri = $this->urlPrefix.$url; return $uri === '/' ? '/' : ltrim(rtrim($uri, '/'), '/'); }
Format URL. @param string $url @return string
public function publish($message) { $serializedMessage = $this->serializer->wrapAndSerialize($message); $routingKey = $this->routingKeyResolver->resolveRoutingKeyFor($message); $additionalProperties = $this->additionalPropertiesResolver->resolveAdditionalPropertiesFor($message); $this->producer->publish($serializedMessage, $routingKey, $additionalProperties); }
Publish the given Message by serializing it and handing it over to a RabbitMQ producer @{inheritdoc}
public function handleProviderCallback(Request $request, string $provider) { $providerUser = Socialite::driver($provider)->user(); $fullName = explode(' ', $providerUser->name); $attributes = [ 'id' => $providerUser->id, 'email' => $providerUser->email, 'username' => $providerUser->nickname ?? trim(mb_strstr($providerUser->email, '@', true)), 'given_name' => current($fullName), 'family_name' => end($fullName), ]; switch ($provider) { case 'twitter': $attributes['title'] = $providerUser->user['description']; $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'github': $attributes['title'] = $providerUser->user['bio']; $attributes['profile_picture'] = $providerUser->avatar; break; case 'facebook': $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'linkedin': $attributes['title'] = $providerUser->headline; $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'google': $attributes['title'] = $providerUser->tagline; $attributes['profile_picture'] = $providerUser->avatar_original; break; } if (! ($localUser = $this->getLocalUser($provider, $providerUser->id))) { $localUser = $this->createLocalUser($provider, $attributes); } auth()->guard($this->getGuard())->login($localUser, true); return intend([ 'intended' => route('adminarea.home'), 'with' => ['success' => trans('cortex/auth::messages.auth.login')], ]); }
Obtain the user information from Provider. @param \Illuminate\Http\Request $request @param string $provider @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
protected function getLocalUser(string $provider, string $providerUserId) { return app('cortex.auth.admin')->whereHas('socialites', function (Builder $builder) use ($provider, $providerUserId) { $builder->where('provider', $provider)->where('provider_uid', $providerUserId); })->first(); }
Get local user for the given provider. @param string $provider @param string $providerUserId @return \Illuminate\Database\Eloquent\Model|null
public function terminate($request, $response): void { if ($user = $request->user(request()->route('guard'))) { // We are using database queries rather than eloquent, to bypass triggering events. // Triggering update events flush cache and costs us more queries, which we don't need. $user->newQuery()->where($user->getKeyName(), $user->getKey())->update(['last_activity' => now()]); } }
Perform any final actions for the request lifecycle. @param \Illuminate\Http\Request $request @param \Symfony\Component\HttpFoundation\Response $response @return void
public function boot() { // Load resources $this->loadViewsFrom(__DIR__.'/../../resources/views', 'rinvex/menus'); // Register core presenters $this->app['rinvex.menus.presenters']->put('navbar', \Rinvex\Menus\Presenters\NavbarPresenter::class); $this->app['rinvex.menus.presenters']->put('navbar-right', \Rinvex\Menus\Presenters\NavbarRightPresenter::class); $this->app['rinvex.menus.presenters']->put('nav-pills', \Rinvex\Menus\Presenters\NavPillsPresenter::class); $this->app['rinvex.menus.presenters']->put('nav-tab', \Rinvex\Menus\Presenters\NavTabPresenter::class); $this->app['rinvex.menus.presenters']->put('sidebar', \Rinvex\Menus\Presenters\SidebarMenuPresenter::class); $this->app['rinvex.menus.presenters']->put('navmenu', \Rinvex\Menus\Presenters\NavMenuPresenter::class); $this->app['rinvex.menus.presenters']->put('adminlte', \Rinvex\Menus\Presenters\AdminltePresenter::class); // Publish Resources ! $this->app->runningInConsole() || $this->publishResources(); }
Bootstrap the application events.
public function register() { // Register menus service $this->app->singleton('rinvex.menus', MenuManager::class); // Register menu presenters service $this->app->singleton('rinvex.menus.presenters', function ($app) { return collect(); }); }
Register the service provider.
public function toMail($notifiable): MailMessage { return (new MailMessage()) ->subject(trans('cortex/auth::emails.auth.lockout.subject')) ->line(trans('cortex/auth::emails.auth.lockout.intro', ['created_at' => now(), 'ip' => $this->ip, 'agent' => $this->agent])) ->line(trans('cortex/auth::emails.auth.lockout.outro')); }
Build the mail representation of the notification. @param mixed $notifiable @return \Illuminate\Notifications\Messages\MailMessage
public function hashPassword($plaintext, array $options = array()) { // Use the password extension if able if (version_compare(PHP_VERSION, '7.2', '>=') && \defined('PASSWORD_ARGON2I')) { return password_hash($plaintext, PASSWORD_ARGON2I, $options); } // Use the sodium extension (PHP 7.2 native or PECL 2.x) if able if (\function_exists('sodium_crypto_pwhash_str_verify')) { $hash = sodium_crypto_pwhash_str( $plaintext, SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE ); sodium_memzero($plaintext); return $hash; } // Use the libsodium extension (PECL 1.x) if able if (\extension_loaded('libsodium')) { $hash = \Sodium\crypto_pwhash_str( $plaintext, \Sodium\CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, \Sodium\CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE ); \Sodium\memzero($plaintext); return $hash; } throw new \LogicException('Argon2i algorithm is not supported.'); }
Generate a hash for a plaintext password @param string $plaintext The plaintext password to validate @param array $options Options for the hashing operation @return string @since 1.2.0 @throws \LogicException
public static function isSupported() { // Check for native PHP engine support in the password extension if (version_compare(PHP_VERSION, '7.2', '>=') && \defined('PASSWORD_ARGON2I')) { return true; } // Check if the sodium_compat polyfill is installed and look for compatibility through that if (class_exists('\\ParagonIE_Sodium_Compat') && method_exists('\\ParagonIE_Sodium_Compat', 'crypto_pwhash_is_available')) { return \ParagonIE_Sodium_Compat::crypto_pwhash_is_available(); } // Check for support from the (lib)sodium extension return \function_exists('sodium_crypto_pwhash_str') || \extension_loaded('libsodium'); }
Check that the password handler is supported in this environment @return boolean @since 1.2.0
public function validatePassword($plaintext, $hashed) { // Use the password extension if able if (version_compare(PHP_VERSION, '7.2', '>=') && \defined('PASSWORD_ARGON2I')) { return password_verify($plaintext, $hashed); } // Use the sodium extension (PHP 7.2 native or PECL 2.x) if able if (\function_exists('sodium_crypto_pwhash_str_verify')) { $valid = sodium_crypto_pwhash_str_verify($hashed, $plaintext); sodium_memzero($plaintext); return $valid; } // Use the libsodium extension (PECL 1.x) if able if (\extension_loaded('libsodium')) { $valid = \Sodium\crypto_pwhash_str_verify($hashed, $plaintext); \Sodium\memzero($plaintext); return $valid; } throw new \LogicException('Argon2i algorithm is not supported.'); }
Validate a password @param string $plaintext The plain text password to validate @param string $hashed The password hash to validate against @return boolean @since 1.2.0 @throws \LogicException
public function login(AuthenticationRequest $request) { // Prepare variables $loginField = get_login_field($request->input($this->username())); $credentials = [ 'is_active' => true, $loginField => $request->input('loginfield'), 'password' => $request->input('password'), ]; // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. if ($this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return $this->sendLockoutResponse($request); } if (auth()->guard($this->getGuard())->attempt($credentials, $request->filled('remember'))) { return $this->sendLoginResponse($request); } // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. $this->incrementLoginAttempts($request); return $this->sendFailedLoginResponse($request); }
Process to the login form. @param \Cortex\Auth\Http\Requests\Adminarea\AuthenticationRequest $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
protected function sendLoginResponse(Request $request) { $user = auth()->guard($this->getGuard())->user(); $twofactor = $user->getTwoFactor(); $totpStatus = $twofactor['totp']['enabled'] ?? false; $phoneStatus = $twofactor['phone']['enabled'] ?? false; $request->session()->regenerate(); $this->clearLoginAttempts($request); // Enforce TwoFactor authentication if ($totpStatus || $phoneStatus) { $this->processLogout($request); $request->session()->put('cortex.auth.twofactor', ['user_id' => $user->getKey(), 'remember' => $request->filled('remember'), 'totp' => $totpStatus, 'phone' => $phoneStatus]); $route = $totpStatus ? route('adminarea.verification.phone.verify') : route('adminarea.verification.phone.request'); return intend([ 'url' => $route, 'with' => ['warning' => trans('cortex/auth::messages.verification.twofactor.totp.required')], ]); } return intend([ 'intended' => route('adminarea.home'), 'with' => ['success' => trans('cortex/auth::messages.auth.login')], ]); }
Send the response after the user was authenticated. @param \Illuminate\Http\Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
protected function processLogout(Request $request): void { auth()->guard($this->getGuard())->logout(); $request->session()->invalidate(); }
Process logout. @param \Illuminate\Http\Request $request @return void
public function authorize(): bool { parent::authorize(); $user = $this->user($this->route('guard')) ?? $this->attemptUser($this->route('guard')) ?? app('cortex.auth.admin')->whereNotNull('phone')->where('phone', $this->get('phone'))->first(); if (! $user) { // User instance required to detect active TwoFactor methods throw new GenericException(trans('cortex/foundation::messages.session_required'), route('adminarea.login')); } return true; }
Determine if the user is authorized to make this request. @throws \Cortex\Foundation\Exceptions\GenericException @return bool
protected function attachRequestMacro(): void { Request::macro('attemptUser', function (string $guard = null) { $twofactor = $this->session()->get('cortex.auth.twofactor'); return auth()->guard($guard)->getProvider()->retrieveById($twofactor['user_id']); }); }
Register console commands. @return void
protected function overrideMiddleware(Router $router): void { // Append middleware to the 'web' middlware group $router->pushMiddlewareToGroup('web', UpdateLastActivity::class); // Override route middleware on the fly $router->aliasMiddleware('reauthenticate', Reauthenticate::class); $router->aliasMiddleware('guest', RedirectIfAuthenticated::class); }
Override middleware. @param \Illuminate\Routing\Router $router @return void
public function rules(): array { $user = $this->route('ability') ?? new Ability(); $user->updateRulesUniques(); $rules = $user->getRules(); $rules['roles'] = 'nullable|array'; return $rules; }
Get the validation rules that apply to the request. @return array
public function getChildMenuItems(MenuItem $item): string { $results = ''; foreach ($item->getChilds() as $child) { if ($child->isHidden()) { continue; } if ($child->hasChilds()) { $results .= $this->getMultiLevelDropdownWrapper($child); } elseif ($child->isHeader()) { $results .= $this->getHeaderWrapper($child); } elseif ($child->isDivider()) { $results .= $this->getDividerWrapper(); } else { $results .= $this->getMenuWithoutDropdownWrapper($child); } } return $results; }
Get child menu items. @param \Rinvex\Menus\Models\MenuItem $item @return string
public function authenticate() { $username = $this->input->get('username', false, 'username'); $password = $this->input->get('password', false, 'raw'); if (!$username || !$password) { $this->status = Authentication::NO_CREDENTIALS; return false; } return $this->doAuthenticate($username, $password); }
Attempt to authenticate the username and password pair. @return string|boolean A string containing a username if authentication is successful, false otherwise. @since 1.1.0
protected function getHashedPassword($username) { $password = $this->db->setQuery( $this->db->getQuery(true) ->select($this->dbOptions['password_column']) ->from($this->dbOptions['database_table']) ->where($this->dbOptions['username_column'] . ' = ' . $this->db->quote($username)) )->loadResult(); if (!$password) { return false; } return $password; }
Retrieve the hashed password for the specified user. @param string $username Username to lookup. @return string|boolean Hashed password on success or boolean false on failure. @since 1.1.0
public function url(string $url, string $title, int $order = null, string $icon = null, array $attributes = []) { return $this->add(compact('url', 'title', 'order', 'icon', 'attributes')); }
Register new menu item using url. @param string $url @param string $title @param int $order @param string $icon @param array $attributes @return static
public function header(string $title, int $order = null, string $icon = null, array $attributes = []) { $type = 'header'; return $this->add(compact('type', 'url', 'title', 'order', 'icon', 'attributes')); }
Add new header item. @param string $title @param int $order @param string $icon @param array $attributes @return static
public function getUrl(): string { return $this->route ? route($this->route[0], $this->route[1] ?? []) : ($this->url ? url($this->url) : ''); }
Get url. @return string
public function ifCan(string $ability, $params = null, $guard = null) { $this->hideCallbacks->push(function () use ($ability, $params, $guard) { return ! optional(auth()->guard($guard)->user())->can($ability, $params); }); return $this; }
Set authorization callback for current menu item. @param string $ability @param mixed $params @param string $guard @return $this
public function ifUser($guard = null) { $this->hideCallbacks->push(function () use ($guard) { return ! auth()->guard($guard)->user(); }); return $this; }
Set authentication callback for current menu item. @param string $guard @return $this
public function ifGuest($guard = null) { $this->hideCallbacks->push(function () use ($guard) { return auth()->guard($guard)->user(); }); return $this; }
Set authentication callback for current menu item. @param string $guard @return $this
public function isActive(): bool { if (is_callable($activeWhen = $this->activeWhen)) { return call_user_func($activeWhen); } if ($this->route) { return $this->hasActiveStateFromRoute(); } return $this->hasActiveStateFromUrl(); }
Get active state for current item. @return bool
public function activateOnRoute(string $route) { $this->activeWhen = function () use ($route) { return str_contains(Route::currentRouteName(), $route); }; return $this; }
Set active callback on the given route. @param string $route @return $this
protected function add(array $properties = []) { $properties['attributes']['id'] = $properties['attributes']['id'] ?? md5(json_encode($properties)); $this->childs->push($item = new static($properties)); return $item; }
Add new child item. @param array $properties @return static
protected function hasActiveStateFromChilds(): bool { return $this->getChilds()->contains(function (MenuItem $child) { return ($child->hasChilds() && $child->hasActiveStateFromChilds()) || ($child->route && $child->hasActiveStateFromRoute()) || $child->isActive() || $child->hasActiveStateFromUrl(); }) ?? false; }
Check if the item has active state from childs. @return bool
public function up(): void { Schema::create(config('cortex.auth.tables.members'), function (Blueprint $table) { // Columns $table->increments('id'); $table->string('given_name'); $table->string('family_name')->nullable(); $table->string('email'); $table->string('username'); $table->string('password'); $table->rememberToken(); $table->timestamp('email_verified_at')->nullable(); $table->string('phone')->nullable(); $table->timestamp('phone_verified_at')->nullable(); $table->string('title')->nullable(); $table->string('organization')->nullable(); $table->string('country_code', 2)->nullable(); $table->string('language_code', 2)->nullable(); $table->text('two_factor')->nullable(); $table->date('birthday')->nullable(); $table->string('gender')->nullable(); $table->schemalessAttributes('social'); $table->boolean('is_active')->default(true); $table->timestamp('last_activity')->nullable(); $table->auditableAndTimestamps(); $table->softDeletes(); }); }
Run the migrations. @return void
private function isClassName($value, array $options) { if (preg_match('/^([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\\\\(?1))*$/', $value) !== 1) { return false; } return array_intersect(iterator_to_array($this->iterateNamespaces($value)), $options['string.classes']) !== []; }
Tests if the given value is a string that could be encoded as a class name constant. @param string $value The string to test @param array $options The string encoding options @return bool True if string can be encoded as class constant, false if not
private function getClassName($value, array $options) { foreach ($this->iterateNamespaces($value) as $partial) { if (isset($options['string.imports'][$partial])) { $trimmed = substr($value, \strlen(rtrim($partial, '\\'))); return ltrim(sprintf('%s%s::class', rtrim($options['string.imports'][$partial], '\\'), $trimmed), '\\'); } } return sprintf('\\%s::class', $value); }
Encodes the given string as a class name constant based on used imports. @param string $value The string to encode @param array $options The string encoding options @return string The class constant PHP code representation
private function iterateNamespaces($value) { yield $value; $parts = explode('\\', '\\' . $value); $count = \count($parts); for ($i = 1; $i < $count; $i++) { yield ltrim(implode('\\', \array_slice($parts, 0, -$i)), '\\') . '\\'; } }
Iterates over the variations of the namespace for the given class name. @param string $value The class name to iterate over @return \Generator|string[] The namespace parts of the string
private function getComplexString($value, array $options) { if ($this->isBinaryString($value, $options)) { return $this->encodeBinaryString($value); } if ($options['string.escape']) { return $this->getDoubleQuotedString($value, $options); } return $this->getSingleQuotedString($value); }
Returns the PHP code representation for the string that is not just simple ascii characters. @param string $value The string to encode @param array $options The string encoding options @return string The PHP code representation for the complex string
private function getDoubleQuotedString($string, $options) { $string = strtr($string, [ "\n" => '\n', "\r" => '\r', "\t" => '\t', '$' => '\$', '"' => '\"', '\\' => '\\\\', ]); if ($options['string.utf8']) { $string = $this->encodeUtf8($string, $options); } $hexFormat = function ($matches) use ($options) { return sprintf($options['hex.capitalize'] ? '\x%02X' : '\x%02x', \ord($matches[0])); }; return sprintf('"%s"', preg_replace_callback('/[^\x20-\x7E]/', $hexFormat, $string)); }
Returns the string wrapped in double quotes and all but print characters escaped. @param string $string String to wrap and escape @param array $options The string encoding options @return string The string wrapped in double quotes and escape correctly
private function encodeUtf8($string, $options) { $pattern = '/ [\xC2-\xDF][\x80-\xBF] | \xE0[\xA0-\xBF][\x80-\xBF] | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} | \xED[\x80-\x9F][\x80-\xBF] | \xF0[\x90-\xBF][\x80-\xBF]{2} | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2}/x'; return preg_replace_callback($pattern, function ($match) use ($options) { return sprintf($options['hex.capitalize'] ? '\u{%X}' : '\u{%x}', $this->getCodePoint($match[0])); }, $string); }
Encodes all multibyte UTF-8 characters into PHP7 string encoding. @param string $string The string to encoder @param array $options The string encoding options @return string The string with all the multibyte characters encoded
private function getCodePoint($bytes) { if (\strlen($bytes) === 2) { return ((\ord($bytes[0]) & 0b11111) << 6) | (\ord($bytes[1]) & 0b111111); } if (\strlen($bytes) === 3) { return ((\ord($bytes[0]) & 0b1111) << 12) | ((\ord($bytes[1]) & 0b111111) << 6) | (\ord($bytes[2]) & 0b111111); } return ((\ord($bytes[0]) & 0b111) << 18) | ((\ord($bytes[1]) & 0b111111) << 12) | ((\ord($bytes[2]) & 0b111111) << 6) | (\ord($bytes[3]) & 0b111111); }
Returns the unicode code point for the given multibyte UTF-8 character. @param string $bytes The multibyte character @return int The code point for the multibyte character
public function handle($request, Closure $next, $guard = null) { if (auth()->guard($guard)->check()) { return intend([ 'url' => route($request->route('accessarea').'.home'), 'with' => ['success' => trans('cortex/foundation::messages.already_authenticated')], ]); } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @param string|null $guard @return mixed
public function setTenantsAttribute($tenants): void { static::saved(function (self $model) use ($tenants) { $tenants = collect($tenants)->filter(); $model->tenants->pluck('id')->similar($tenants) || activity() ->performedOn($model) ->withProperties(['attributes' => ['tenants' => $tenants], 'old' => ['tenants' => $model->tenants->pluck('id')->toArray()]]) ->log('updated'); $model->syncTenants($tenants); }); }
Attach the given tenants to the model. @param mixed $tenants @return void
public function define($blueprint_name, $defaults, $associations = array()) { if($defaults instanceof Blueprint) { $blueprint = $defaults; } else { $blueprint = new Blueprint($blueprint_name, $defaults, $associations, $this); } $this->_blueprints[$blueprint_name] = $blueprint; }
/* Define the default values to use when constructing a document in the specified collection. @param string $blueprint_name singular name of the collection in the database @param array $defaults key => value pairs of field => value, or a phactory_blueprint @param array $associations array of phactory_associations
public function createWithAssociations($blueprint_name, $associations = array(), $overrides = array()) { if(! ($blueprint = $this->_blueprints[$blueprint_name]) ) { throw new \Exception("No blueprint defined for '$blueprint_name'"); } return $blueprint->create($overrides, $associations); }
/* Instantiate a document in the specified collection, optionally overriding some or all of the default values. The document is saved to the database, and returned as an array. @param string $blueprint_name name of the blueprint to use @param array $associations [collection name] => [array] @param array $overrides key => value pairs of field => value @return array
public function buildWithAssociations($blueprint_name, $associations = array(), $overrides = array()) { if(! ($blueprint = $this->_blueprints[$blueprint_name]) ) { throw new \Exception("No blueprint defined for '$blueprint_name'"); } return $blueprint->build($overrides, $associations); }
/* Build a document as an array, optionally overriding some or all of the default values. The document is not saved to the database. @param string $blueprint_name name of the blueprint to use @param array $associations [collection name] => [array] @param array $overrides key => value pairs of field => value @return array
public function get($collection_name, $query) { if(!is_array($query)) { throw new \Exception("\$query must be an associative array of 'field => value' pairs"); } $collection = new Collection($collection_name, true, $this); return $collection->findOne($query); }
/* Get a document from the database as an array. @param string $collection_name name of the collection @param array $query a MongoDB query @return array
public function getAll($collection_name, $query = array()) { if(!is_array($query)) { throw new \Exception("\$query must be an associative array of 'field => value' pairs"); } $collection = new Collection($collection_name, true, $this); return $collection->find($query); }
/* Get results from the database as a cursor. @param string $collection_name name of the collection @param array $query a MongoDB query @return MongoCursor
public function messageConsumptionFailed(MessageConsumptionFailed $event) { $this->logger->log( $this->logLevel, $this->logMessage, [ 'exception' => $event->exception(), 'message' => $event->message() ] ); }
Log the failed message and the related exception
public function scopeGuestsBySeconds(Builder $builder, $seconds = 60): Builder { return $builder->where('last_activity', '>=', time() - $seconds)->whereNull('user_id'); }
Constrain the query to retrieve only sessions of guests who have been active within the specified number of seconds. @param \Illuminate\Database\Eloquent\Builder $builder @param int $seconds @return \Illuminate\Database\Eloquent\Builder
public function scopeUsersBySeconds(Builder $builder, $seconds = 60): Builder { return $builder->with(['user'])->where('last_activity', '>=', now()->subSeconds($seconds))->whereNotNull('user_id'); }
Constrain the query to retrieve only sessions of users who have been active within the specified number of seconds. @param \Illuminate\Database\Eloquent\Builder $builder @param int $seconds @return \Illuminate\Database\Eloquent\Builder
public function withValidator($validator): void { $user = $this->user($this->route('guard')); $validator->after(function ($validator) use ($user) { if (! $user->phone || ! $user->hasVerifiedPhone()) { $validator->errors()->add('phone', trans('cortex/auth::messages.account.'.(! $user->phone ? 'phone_field_required' : 'phone_verification_required'))); } }); }
Configure the validator instance. @param \Illuminate\Validation\Validator $validator @return void
public function destroy(Admin $admin, Media $media) { $admin->media()->where($media->getKeyName(), $media->getKey())->first()->delete(); return intend([ 'url' => route('adminarea.admins.edit', ['admin' => $admin]), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/foundation::common.media'), 'identifier' => $media->getRouteKey()])], ]); }
Destroy given admin media. @param \Cortex\Auth\Models\Admin $admin @param \Spatie\MediaLibrary\Models\Media $media @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function build($overrides = array(), $associated = array()) { // process one-to-one and many-to-one relations $assoc_keys = array(); foreach($associated as $name => $row) { if(!isset($this->_associations[$name])) { throw new \Exception("No association '$name' defined"); } $association = $this->_associations[$name]; if(!$association instanceof Association\ManyToMany) { $fk_column = $association->getFromColumn(); $to_column = $association->getToColumn(); $assoc_keys[$fk_column] = $row->$to_column; } } $data = array_merge($this->_defaults, $assoc_keys); $this->_evalSequence($data); $built = new Row($this->_table, $data, $this->_phactory); if($overrides) { foreach($overrides as $field => $value) { $built->$field = $value; } } return $built; }
/* Build a Row from this Blueprint. Optionally use an array of associated objects to set fk columns. Note that this function ignores ManyToMany associations, as those can't be handled unless the Row is actually saved to the db. @param array $associated [table name] => [Row]
public function create($overrides = array(), $associated = array()) { $built = $this->build($overrides, $associated); // process any many-to-many associations $many_to_many = array(); foreach($associated as $name => $row) { $association = $this->_associations[$name]; if($association instanceof Association\ManyToMany) { if(!is_array($row)) { $row = array($row); } $many_to_many[$name] = array($row, $association); } } $built->save(); if($many_to_many) { $this->_associateManyToMany($built, $many_to_many); } return $built; }
/* Reify a Blueprint as a Row. Optionally use an array of associated objects to set fk columns. @param array $associated [table name] => [Row]
public function recall() { $db_util = DbUtilFactory::getDbUtil($this->_phactory); $db_util->disableForeignKeys(); try { $sql = "DELETE FROM {$this->_table->getName()}"; $this->_phactory->getConnection()->exec($sql); } catch(Exception $e) { } foreach($this->_associations as $association) { if($association instanceof Association\ManyToMany) { try { $sql = "DELETE FROM `{$association->getJoinTable()}`"; $this->_phactory->getConnection()->exec($sql); } catch(Exception $e) { } } } $db_util->enableForeignKeys(); }
/* Truncate table in the database.
public function hashPassword($plaintext, array $options = array()) { // Use the password extension if able if (version_compare(PHP_VERSION, '7.3', '>=') && \defined('PASSWORD_ARGON2ID')) { return password_hash($plaintext, PASSWORD_ARGON2ID, $options); } throw new \LogicException('Argon2id algorithm is not supported.'); }
Generate a hash for a plaintext password @param string $plaintext The plaintext password to validate @param array $options Options for the hashing operation @return string @since 1.3.0 @throws \LogicException
public function validatePassword($plaintext, $hashed) { // Use the password extension if able if (version_compare(PHP_VERSION, '7.3', '>=') && \defined('PASSWORD_ARGON2ID')) { return password_verify($plaintext, $hashed); } throw new \LogicException('Argon2id algorithm is not supported.'); }
Validate a password @param string $plaintext The plain text password to validate @param string $hashed The password hash to validate against @return boolean @since 1.3.0 @throws \LogicException
public function import(Guardian $guardian, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $guardian, 'tabs' => 'adminarea.guardians.tabs', 'url' => route('adminarea.guardians.stash'), 'id' => "adminarea-attributes-{$guardian->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
Import guardians. @param \Cortex\Auth\Models\Guardian $guardian @param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable @return \Illuminate\View\View
protected function form(Request $request, Guardian $guardian) { $tags = app('rinvex.tags.tag')->pluck('name', 'id'); return view('cortex/auth::adminarea.pages.guardian', compact('guardian', 'tags')); }
Show guardian create/edit form. @param \Illuminate\Http\Request $request @param \Cortex\Auth\Models\Guardian $guardian @return \Illuminate\View\View
protected function process(FormRequest $request, Guardian $guardian) { // Prepare required input fields $data = $request->validated(); // Save guardian $guardian->fill($data)->save(); return intend([ 'url' => route('adminarea.guardians.index'), 'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/auth::common.guardian'), 'identifier' => $guardian->username])], ]); }
Process stored/updated guardian. @param \Illuminate\Foundation\Http\FormRequest $request @param \Cortex\Auth\Models\Guardian $guardian @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function destroy(Guardian $guardian) { $guardian->delete(); return intend([ 'url' => route('adminarea.guardians.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.guardian'), 'identifier' => $guardian->username])], ]); }
Destroy given guardian. @param \Cortex\Auth\Models\Guardian $guardian @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
protected function attemptTwoFactor(AuthenticatableTwoFactorContract $user, int $token): bool { return $this->isValidTwoFactorTotp($user, $token) || $this->isValidTwoFactorBackup($user, $token) || $this->isValidTwoFactorPhone($user, $token); }
Verify TwoFactor authentication. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return bool
protected function invalidateTwoFactorBackup(AuthenticatableTwoFactorContract $user, int $token): void { $settings = $user->getTwoFactor(); $backup = array_get($settings, 'totp.backup'); unset($backup[array_search($token, $backup)]); array_set($settings, 'totp.backup', $backup); // Update TwoFactor OTP backup codes $user->fill(['two_factor' => $settings])->forceSave(); }
Invalidate given backup code for the given user. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return void
protected function isValidTwoFactorPhone(AuthenticatableTwoFactorContract $user, int $token): bool { $settings = $user->getTwoFactor(); $authyId = array_get($settings, 'phone.authy_id'); return in_array(mb_strlen($token), [6, 7, 8]) && app('rinvex.authy.token')->verify($token, $authyId)->succeed(); }
Determine if the given token is a valid TwoFactor Phone token. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return bool
protected function isValidTwoFactorBackup(AuthenticatableTwoFactorContract $user, int $token): bool { $backup = array_get($user->getTwoFactor(), 'totp.backup', []); $result = mb_strlen($token) === 10 && in_array($token, $backup); ! $result || $this->invalidateTwoFactorBackup($user, $token); return $result; }
Determine if the given token is a valid TwoFactor Backup code. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return bool
protected function isValidTwoFactorTotp(AuthenticatableTwoFactorContract $user, int $token): bool { $totpProvider = app(Google2FA::class); $secret = array_get($user->getTwoFactor(), 'totp.secret'); return mb_strlen($token) === 6 && $totpProvider->verifyKey($secret, $token); }
Determine if the given token is a valid TwoFactor TOTP token. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return bool
public function handle(): void { $this->warn($this->description); $this->call('db:seed', ['--class' => 'CortexAuthSeeder']); // Create models $admin = $this->createAdmin($adminPassword = str_random()); $guardian = $this->createGuardian($guardianPassword = str_random()); // Assign roles $admin->assign('superadmin'); $this->table(['Username', 'Password'], [ ['username' => $admin['username'], 'password' => $adminPassword], ['username' => $guardian['username'], 'password' => $guardianPassword], ]); }
Execute the console command. @return void
protected function createAdmin(string $password): Admin { $admin = [ 'is_active' => true, 'username' => 'Admin', 'given_name' => 'Admin', 'family_name' => 'User', 'email' => 'admin@example.com', ]; return tap(app('cortex.auth.admin')->firstOrNew($admin)->fill([ 'remember_token' => str_random(10), 'email_verified_at' => now(), 'password' => $password, ]), function ($instance) { $instance->save(); }); }
Create admin model. @param string $password @return \Cortex\Auth\Models\Admin
protected function createGuardian(string $password): Guardian { $guardian = [ 'is_active' => true, 'username' => 'Guardian', 'email' => 'guardian@example.com', ]; return tap(app('cortex.auth.guardian')->firstOrNew($guardian)->fill([ 'remember_token' => str_random(10), 'password' => $password, ]), function ($instance) { $instance->save(); }); }
Create guardian model. @param string $password @return \Cortex\Auth\Models\Guardian
public function toAuthy(): AuthyMessage { $message = AuthyMessage::create()->method($this->method); if ($this->force) { $message->force(); } return $message; }
Build the mail representation of the notification. @return \NotificationChannels\Authy\AuthyMessage
public function setAbilitiesAttribute($abilities): void { static::saved(function (self $model) use ($abilities) { $abilities = collect($abilities)->filter(); $model->abilities->pluck('id')->similar($abilities) || activity() ->performedOn($model) ->withProperties(['attributes' => ['abilities' => $abilities], 'old' => ['abilities' => $model->abilities->pluck('id')->toArray()]]) ->log('updated'); $model->abilities()->sync($abilities, true); }); }
Attach the given abilities to the model. @param mixed $abilities @return void
public function setRolesAttribute($roles): void { static::saved(function (self $model) use ($roles) { $roles = collect($roles)->filter(); $model->roles->pluck('id')->similar($roles) || activity() ->performedOn($model) ->withProperties(['attributes' => ['roles' => $roles], 'old' => ['roles' => $model->roles->pluck('id')->toArray()]]) ->log('updated'); $model->roles()->sync($roles, true); }); }
Attach the given roles to the model. @param mixed $roles @return void
protected static function boot() { parent::boot(); static::saving(function (self $user) { foreach (array_intersect($user->getHashables(), array_keys($user->getAttributes())) as $hashable) { if ($user->isDirty($hashable) && Hash::needsRehash($user->{$hashable})) { $user->{$hashable} = Hash::make($user->{$hashable}); } } }); }
{@inheritdoc}
public function routeNotificationForAuthy(): ?int { if (! ($authyId = array_get($this->getTwoFactor(), 'phone.authy_id')) && $this->getEmailForVerification() && $this->getPhoneForVerification() && $this->getCountryForVerification()) { $result = app('rinvex.authy.user')->register($this->getEmailForVerification(), preg_replace('/[^0-9]/', '', $this->getPhoneForVerification()), $this->getCountryForVerification()); $authyId = $result->get('user')['id']; // Prepare required variables $twoFactor = $this->getTwoFactor(); // Update user account array_set($twoFactor, 'phone.authy_id', $authyId); $this->fill(['two_factor' => $twoFactor])->forceSave(); } return $authyId; }
Route notifications for the authy channel. @return int|null
public function getManagedRoles(): Collection { if ($this->isA('superadmin')) { $roles = app('cortex.auth.role')->all(); } elseif ($this->isA('supermanager')) { $roles = $this->roles->merge(config('rinvex.tenants.active') ? app('cortex.auth.role')->where('scope', config('rinvex.tenants.active')->getKey())->get() : collect()); } else { $roles = $this->roles; } return $roles->pluck('title', 'id')->sort(); }
Get managed roles. @return \Illuminate\Support\Collection
public function getManagedAbilities(): Collection { $abilities = $this->isA('superadmin') ? app('cortex.auth.ability')->all() : $this->getAbilities(); return $abilities->groupBy('entity_type')->map->pluck('title', 'id')->sortKeys(); }
Get managed abilites. @return \Illuminate\Support\Collection
public function toMail($notifiable): MailMessage { if (static::$toMailCallback) { return call_user_func(static::$toMailCallback, $notifiable); } $email = $notifiable->getEmailForVerification(); $link = route('managerarea.verification.email.verify')."?email={$email}&expiration={$this->expiration}&token={$this->token}"; return (new MailMessage()) ->subject(trans('cortex/auth::emails.verification.email.subject')) ->line(trans('cortex/auth::emails.verification.email.intro', ['expire' => now()->createFromTimestamp($this->expiration)->diffForHumans()])) ->action(trans('cortex/auth::emails.verification.email.action'), $link) ->line(trans('cortex/auth::emails.verification.email.outro', ['created_at' => now(), 'ip' => request()->ip(), 'agent' => request()->userAgent()])); }
Build the mail representation of the notification. @param mixed $notifiable @return \Illuminate\Notifications\Messages\MailMessage
public function query() { $currentUser = $this->request->user($this->request->route('guard')); $query = $currentUser->isA('superadmin') ? app($this->model)->query() : app($this->model)->query()->whereIn('id', $currentUser->roles->pluck('id')->toArray()); return $this->applyScopes($query); }
Get the query object to be processed by dataTables. @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection
public function updateAttributes(AdminAttributesFormRequest $request, Admin $admin) { $data = $request->validated(); // Update profile $admin->fill($data)->save(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.account.updated_attributes')], ]); }
Process the account update form. @param \Cortex\Auth\Http\Requests\Adminarea\AdminAttributesFormRequest $request @param \Cortex\Auth\Models\Admin $admin @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function import(Admin $admin, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $admin, 'tabs' => 'adminarea.admins.tabs', 'url' => route('adminarea.admins.stash'), 'id' => "adminarea-attributes-{$admin->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
Import admins. @param \Cortex\Auth\Models\Admin $admin @param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable @return \Illuminate\View\View
public function destroy(Admin $admin) { $admin->delete(); return intend([ 'url' => route('adminarea.admins.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.admin'), 'identifier' => $admin->username])], ]); }
Destroy given admin. @param \Cortex\Auth\Models\Admin $admin @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function authenticate($strategies = array()) { if (empty($strategies)) { $strategyObjects = $this->strategies; } else { $strategies = (array) $strategies; $strategyObjects = array(); foreach ($strategies as $strategy) { if (!isset($this->strategies[$strategy])) { throw new \RuntimeException('Authentication Strategy Not Found'); } $strategyObjects[$strategy] = $this->strategies[$strategy]; } } if (empty($strategyObjects)) { throw new \RuntimeException('No strategies have been set'); } /** @var AuthenticationStrategyInterface $strategyObject */ foreach ($strategyObjects as $strategy => $strategyObject) { $username = $strategyObject->authenticate(); $this->results[$strategy] = $strategyObject->getResult(); if (\is_string($username)) { return $username; } } return false; }
Perform authentication @param AuthenticationStrategyInterface[] $strategies Array of strategies to try - empty to try all strategies. @return string|boolean A string containing a username if authentication is successful, false otherwise. @since 1.0 @throws \RuntimeException
public static function extract() { return array( 'clientId' => self::extractClientId(), 'ip' => self::extractIp(), 'headers' => self::extractHeaders(), 'user_agent' => self::extractUserAgent(), 'library' => array( 'name' => 'castle-php', 'version' => Castle::VERSION ) ); }
# Extract a request context from the $Server environment.
protected function form(Request $request, Role $role) { $abilities = $request->user($this->getGuard())->getManagedAbilities(); return view('cortex/auth::adminarea.pages.role', compact('role', 'abilities')); }
Show role create/edit form. @param \Illuminate\Http\Request $request @param \Cortex\Auth\Models\Role $role @return \Illuminate\View\View
protected function process(FormRequest $request, Role $role) { // Prepare required input fields $data = $request->validated(); // Save role $role->fill($data)->save(); return intend([ 'url' => route('adminarea.roles.index'), 'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/auth::common.role'), 'identifier' => $role->title])], ]); }
Process stored/updated role. @param \Illuminate\Foundation\Http\FormRequest $request @param \Cortex\Auth\Models\Role $role @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public static function language($code, $hydrate = true) { $code = mb_strtolower($code); if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } if (! isset(static::$languages[$code])) { throw LanguageLoaderException::invalidLanguage(); } return $hydrate ? new Language(static::$languages[$code]) : static::$languages[$code]; }
Get the language by it's ISO ISO 639-1 code. @param string $code @param bool $hydrate @throws \Rinvex\Language\LanguageLoaderException @return \Rinvex\Language\Language|array
public static function languages($hydrate = false) { if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } return $hydrate ? array_map(function ($language) { return new Language($language); }, static::$languages) : static::$languages; }
Get all languages. @param bool $hydrate @return array
public static function scripts() { if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } return static::pluck(static::$languages, 'script.name', 'script.iso_15924'); }
Get all language scripts. @return array
public static function families() { if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } return static::pluck(static::$languages, 'family.name', 'family.iso_639_5'); }
Get all language families. @return array
public function up(): void { Schema::create(config('session.table'), function (Blueprint $table) { // Columns $table->string('id'); $table->nullableMorphs('user'); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->text('payload'); $table->integer('last_activity'); // Indexes $table->unique('id'); }); }
Run the migrations. @return void
public function withValidator($validator): void { $validator->after(function ($validator) { if (! auth()->guard($this->route('guard'))->getProvider()->validateCredentials($this->user($this->route('guard')), ['password' => $this->get('old_password')])) { $validator->errors()->add('old_password', trans('cortex/auth::messages.account.wrong_password')); } if (auth()->guard($this->route('guard'))->getProvider()->validateCredentials($this->user($this->route('guard')), ['password' => $this->get('new_password')])) { $validator->errors()->add('new_password', trans('cortex/auth::messages.account.different_password')); } }); }
Configure the validator instance. @param \Illuminate\Validation\Validator $validator @return void
public function authorize(): bool { $currentUser = $this->user($this->route('guard')); if (! $currentUser->isA('superadmin') && $currentUser !== $this->route('admin')) { throw new GenericException(trans('cortex/auth::messages.action_unauthorized'), route('adminarea.admins.index')); } return true; }
Determine if the user is authorized to make this request. @throws \Cortex\Foundation\Exceptions\GenericException @return bool
public function rules(): array { $admin = $this->route('admin') ?? app('cortex.auth.admin'); $admin->updateRulesUniques(); $rules = $admin->getRules(); $rules['roles'] = 'nullable|array'; $rules['abilities'] = 'nullable|array'; $rules['password'] = $admin->exists ? 'confirmed|min:'.config('cortex.auth.password_min_chars') : 'required|confirmed|min:'.config('cortex.auth.password_min_chars'); return $this->isMethod('POST') ? $rules : []; }
Get the validation rules that apply to the request. @return array
public function processPassword(Request $request) { $redirect_url = session('cortex.auth.reauthentication.intended'); $session_name = session('cortex.auth.reauthentication.session_name'); if (Hash::check($request->input('password'), request()->user($this->getGuard())->password)) { $this->setSession($session_name); return intend([ 'intended' => url($redirect_url), ]); } return intend([ 'intended' => url($redirect_url), 'withErrors' => [ 'password' => trans('cortex/auth::messages.auth.failed'), ], ]); }
@param Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function processTwofactor(Request $request) { $redirect_url = session('cortex.auth.reauthentication.intended'); $session_name = session('cortex.auth.reauthentication.session_name'); $user = $request->user($this->getGuard()); $token = (int) $request->input('token'); if ($this->attemptTwoFactor($user, $token)) { $this->setSession($session_name); return intend([ 'intended' => url($redirect_url), ]); } return intend([ 'intended' => url($redirect_url), 'withErrors' => ['token' => trans('cortex/auth::messages.verification.twofactor.invalid_token')], ]); }
@param Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function subscribe(Dispatcher $dispatcher) { $dispatcher->listen(Login::class, self::class.'@login'); $dispatcher->listen(Lockout::class, self::class.'@lockout'); $dispatcher->listen(Registered::class, self::class.'@registered'); }
Register the listeners for the subscriber. @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
public function lockout(Lockout $event): void { if (config('cortex.auth.emails.throttle_lockout')) { switch ($event->request->route('accessarea')) { case 'managerarea': $model = app('cortex.auth.manager'); break; case 'adminarea': $model = app('cortex.auth.admin'); break; case 'frontarea': case 'tenantarea': default: $model = app('cortex.auth.member'); break; } $user = get_login_field($loginfield = $event->request->get('loginfield')) === 'email' ? $model::where('email', $loginfield)->first() : $model::where('username', $loginfield)->first(); ! $user || $user->notify(new AuthenticationLockoutNotification($event->request->ip(), $event->request->server('HTTP_USER_AGENT'))); } }
Listen to the authentication lockout event. @param \Illuminate\Auth\Events\Lockout $event @return void
protected function getHashedPassword($username) { if (!isset($this->credentialStore[$username])) { return false; } return $this->credentialStore[$username]; }
Retrieve the hashed password for the specified user. @param string $username Username to lookup. @return string|boolean Hashed password on success or boolean false on failure. @since 1.1.0
public function destroy(Session $session) { $session->delete(); return intend([ 'back' => true, 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.session'), 'identifier' => $session->getKey()])], ]); }
Destroy given session. @param \Cortex\Auth\Models\Session $session @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function flush(Request $request) { $request->user($this->getGuard())->sessions()->delete(); return intend([ 'back' => true, 'with' => ['warning' => trans('cortex/auth::messages.auth.session.flushed')], ]); }
Flush all sessions. @param \Illuminate\Http\Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
public function edit(Request $request) { $countries = collect(countries())->map(function ($country, $code) { return [ 'id' => $code, 'text' => $country['name'], 'emoji' => $country['emoji'], ]; })->values(); $languages = collect(languages())->pluck('name', 'iso_639_1'); $genders = ['male' => trans('cortex/auth::common.male'), 'female' => trans('cortex/auth::common.female')]; return view('cortex/auth::adminarea.pages.account-settings', compact('countries', 'languages', 'genders')); }
Edit account settings. @param \Illuminate\Http\Request $request @return \Illuminate\View\View