Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

nette-security

БесплатноБез исполняемых скриптовНе проверен

Invoke before implementing or modifying authentication, login/logout or permission checks in Nette. Covers the Authenticator interface, SimpleIdentity…

netteот nette★ 47 звёзд на GitHub

Об этом скилле

Nette Security

Installed with composer require nette/security. The framework registers security.user (Nette\Security\User), security.passwords, security.userStorage, plus security.authenticator / security.authorizator when the security: config section defines them. All are autowired – inject Nette\Security\User or Nette\Security\Passwords by type; in presenters use $this->getUser().

Current names vs. Nette 2.x names

Using an old name still "works" (aliases/deprecated stubs exist), which makes the mistake silent. Always write the current one:

Current (all in Nette\Security\) Deprecated 2.x name
SimpleIdentity Identity
Authenticator IAuthenticator – a different, array-based authenticate(array $credentials) contract; never implement it
Authorizator, Role, Resource IAuthorizator, IRole, IResource
Authenticator::IdentityNotFound, InvalidCredential IDENTITY_NOT_FOUND, INVALID_CREDENTIAL
Authorizator::All, Allow, Deny ALL, ALLOW, DENY
User::LogoutManual, LogoutInactivity LOGOUT_MANUAL/MANUAL, LOGOUT_INACTIVITY/INACTIVITY

Authenticator

// interface Nette\Security\Authenticator – error codes: IdentityNotFound, InvalidCredential, Failure, NotApproved
function authenticate(string $username, string $password): IIdentity;

InvalidCredential is singular, no trailing s. The error code is the exception's second argument:

public function authenticate(string $username, string $password): SimpleIdentity
{
	$row = $this->database->table('users')->where('username', $username)->fetch();
	if (!$row) {
		throw new AuthenticationException('User not found.', self::IdentityNotFound);
	}
	if (!$this->passwords->verify($password, $row->password)) {
		throw new AuthenticationException('Invalid password.', self::InvalidCredential);
	}
	if ($this->passwords->needsRehash($row->password)) { // transparent hash upgrade
		$this->database->table('users')->wherePrimary($row->id)
			->update(['password' => $this->passwords->hash($password)]);
	}

	return new SimpleIdentity($row->id, $row->role, ['name' => $row->username]);
}

Register it as an ordinary service (services: - MyAuthenticator); User picks it up by autowiring. With several authenticators, mark each autowired: self and call $user->setAuthenticator($this->authenticator) before login(). The return type may be narrowed to SimpleIdentity (covariance). SimpleIdentity(string|int $id, string|array|null $roles = null, ?iterable $data = null) – roles accept a single string. Data is read via magic properties ($identity->name) and getData(); IIdentity declares only getId() and getRoles().

Passwords is a service with instance methods

hash(), verify() and needsRehash() are instance methods on the injected service – not static, and not a wrapper to skip in favour of password_hash() / password_verify():

$hash = $passwords->hash($password);       // throws on empty password
$passwords->verify($password, $hash);      // bool
$passwords->needsRehash($hash);            // bool – rehash on successful login

Configure the algorithm by overriding the service, or with the static factories (3.2.6+):

services:
	security.passwords: Nette\Security\Passwords(::PASSWORD_BCRYPT, [cost: 12])
	# or Nette\Security\Passwords::bcrypt(12)
	# or Nette\Security\Passwords::argon2id(memoryCost: 131072, timeCost: 4) – throws NotSupportedException without Argon2

Store hashes in a VARCHAR(255) column – PASSWORD_DEFAULT may change length between PHP versions.

User

$user->login($username, $password);   // or login($identity) directly; throws AuthenticationException
$user->logout();                      // keeps the identity!
$user->logout(true);                  // discards it
$user->getIdentity();                 // ?IIdentity – nullable
$user->getId();                       // string|int|null
$user->getLogoutReason();             // User::LogoutManual | User::LogoutInactivity | null
$user->onLoggedIn[] = fn() => ...;    // event array; also $onLoggedOut

logout() does not clear the identity by default. getIdentity() and getId() keep returning it afterwards, so "identity exists" is not "logged in" – gate on isLoggedIn(). Use logout(true), or set $user->persistIdentity = false / security: authentication: persistIdentity: false to disable retention globally. Cookie storage cannot retain it either way.

isInRole() / getRoles() / isAllowed() work with effective roles: the identity's roles when logged in, otherwise $user->guestRole ('guest'), never the retained identity's roles – so they need no isLoggedIn() guard. Session-id regeneration on login and logout is done by SessionStorage; do not add your own.

Expiration

$user->setExpiration('30 minutes') must be called before login(); null cancels it. It is inactivi

Полный SKILL.md на GitHub

Установить nette-security в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл nette-security?

Invoke before implementing or modifying authentication, login/logout or permission checks in Nette. Covers the Authenticator interface, SimpleIdentity, Nette\Security\User, the Passwords hashing service, Authorizator, Permission ACL (roles, resources, privileges, assertions), IdentityHandler, user storage (session/cookie), login expiration, and the `security:` NEON section (users, roles, resources, rules). Also trigger for sign-in presenters and forms, isAllowed()/isInRole() checks, password hashing or rehashing, AuthenticationException error codes, and stale roles in the session. Not for Nette Forms validation rules nor for HTTP session configuration itself.

Как установить скилл nette-security?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл nette-security запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить nette-security с