Skip to content

Commit

Permalink
Adjusted spacing
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbyoung committed Sep 1, 2017
1 parent 91822a3 commit e20b5c8
Show file tree
Hide file tree
Showing 41 changed files with 513 additions and 0 deletions.
18 changes: 18 additions & 0 deletions authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,19 @@
6. [JWT Ids](#jwt-ids)

<h2 id="introduction">Introduction</h2>

Opulence's authentication library provides many models out of the box that are common to most authentication schemes. Unlike other frameworks, Opulence's authentication library is not coupled at all to the rest of the framework, including the authorization library. So, you may use it in conjunction with 3rd party authentication and authorization libraries. It is meant to provide you with the tools you need to build your authentication scheme. It is very possible that, with community support, these tools can be used to create new or bridge existing OpenID Connect implementations.

<h2 id="subjects">Subjects</h2>

A subject is the entity that is requesting access to a resource. Although a subject could be a user, it could also be something like a system process. So, it's important to distinguish the concept from users. Subjects have [principals](#principals) and the [credentials](#credentials) to prove their authenticity.

<h4 id="principals">Principals</h4>

A principal is a piece of information that identifies a subject. For example, your social security number is one of your principals. Another might be your name. In the world of programming, a principal might be a user Id or username. Opulence requires that exactly one "primary" principal (usually an Id) is set for a subject.

<h4 id="subject-example">Example</h4>

Let's take a look at subjects in Opulence:

```php
Expand All @@ -57,6 +61,7 @@ To grab all roles, call `$subject->getRoles()`.
To check if a subject has a role, call `$subject->hasRole($roleName)`.

<h2 id="credentials">Credentials</h2>

A credential is simply a value or collection of values used to prove a subject's authenticity. For example, this could be a username/password combination or an OAuth2 access token.

Credentials have a type and value(s):
Expand All @@ -75,15 +80,18 @@ To get the type, call `$credential->getType()`.
To get the credential's values, you can either call `$credential->getValues()` to get all of them, or pass in the name of the value you wish to get, eg `$credential->getValue("username")`.

<h4 id="credential-factories">Credential Factories</h4>

Opulence makes it simple to generate JWT-based credentials for a subject. A couple credential factories come with Opulence, and they both implement`Opulence\Authentication\Credentials\Factories\ICredentialFactory`, which defines a single method `ICredentialFactory::createCredentialForSubject($subject)`:

* `Opulence\Authentication\Credentials\Factories\AccessTokenCredentialFactory`
* `Opulence\Authentication\Credentials\Factories\RefreshTokenCredentialFactory`

<h4 id="authenticators">Authenticators</h4>

Authenticators do what their name implies - they authenticate credentials. Not only that, but they also create a `Subject` object on success, or an error message on failure. They all implement `Opulence\Authentication\Credentials\Authenticators\IAuthenticator`.

<h5 id="username-password-authenticator">Username/Password</h5>

To authenticate a username/password combination, pass in a user repository and a role repository:

```php
Expand Down Expand Up @@ -115,6 +123,7 @@ if (!$authenticator->authenticate($credential, $subject, $error)) {
If your passwords also include a pepper, simply pass it as a 3rd parameter to the `UsernamePasswordAuthenticator` constructor.

<h5 id="jwt-authenticator">JWT Authenticator</h5>

Opulence supports authenticating [JSON web tokens](#jwt), which can be useful for authenticating JWT OAuth2 access tokens. The `JwtAuthenticator` requires a [verifier and a verification context](#verifying-jwt).

```php
Expand All @@ -131,9 +140,11 @@ if (!$authenticator->authenticate($credential, $subject, $error)) {
```

<h5 id="jwt-refresh-token-authenticator">JWT Refresh Token Authenticator</h5>

Refresh tokens are used to generate new access tokens when using OAuth2. They are identical to `JwtAuthenticator`, except they also require a refresh token repository parameter. That repository is left to you to create, and it must implement `Opulence\Authentication\Tokens\JsonWebTokens\Orm\IJwtRepository`.

<h2 id="authentication-contexts">Authentication Contexts</h2>

The `Opulence\Authentication\AuthenticationContext` is a simple wrapper that contains the current subject as well as its status, eg authenticated or unauthenticated.

```php
Expand All @@ -160,11 +171,13 @@ $authenticationContext->setStatus(AuthenticationStatusTypes::UNAUTHENTICATED);
```

<h4 id="authentication-context-middleware">Middleware</h4>

Opulence provides the `Opulence\Authentication\Framework\Http\Middleware\Authenticate` middleware to get the current subject from the HTTP request and store it along with its status in an `AuthenticationContext`.

<h2 id="jwt">JSON Web Tokens</h2>

<h4 id="jwt-introduction">Introduction</h4>

JSON web tokens (JWTs) are great ways for passing claims (such as a user's identity) between a client and the server. They consist of three parts:
1. Header - The algorithm used to sign the token, the content type ("JWT"), and the token type ("JWT")
2. Payload - The data actually being sent in the token (also called "claims")
Expand All @@ -174,6 +187,7 @@ JSON web tokens (JWTs) are great ways for passing claims (such as a user's ident
Typically, you'll see JWTs as strings in the following format: "{base64-encoded header}.{base64-encoded payload}.{base64-encoded signature}".

<h4 id="building-jwts">Building JWTs</h4>

You can programmatically build an unsigned JWT. You can then use a signer to [sign your JWT](#signing-jwts) and encode it as a string.

```php
Expand Down Expand Up @@ -205,6 +219,7 @@ $unsignedJwt = new UnsignedJwt($header, $payload);
```

<h4 id="signing-jwts">Signing JWTs</h4>

To encode your JWT, you'll first need to sign it using an `ISigner`.

```php
Expand All @@ -216,6 +231,7 @@ $signedJwt->encode(); // Returns the encoded JWT
```

<h4 id="verifying-jwts">Verifying JWTs</h4>

Verifying a JWT is simple. Create a `VerificationContext` and specify the fields we want to verify against. The verifier will then compare those fields to the JWT's claims. It will also verify that the signature is correct.

```php
Expand All @@ -236,6 +252,7 @@ if (!$verifier->verify($signedJwt, $context, $errors = [])) {
The errors will correspond to the constants in `Opulence\Authentication\Tokens\JsonWebTokens\Verification\JwtErrorTypes`.

<h4 id="creating-jwts-from-strings">Creating JWTs from Strings</h4>

You can easily create a `SignedJwt` from a string in the format "{base64-encoded header}.{base64-encoded payload}.{base64-encoded signature}".

```php
Expand All @@ -245,6 +262,7 @@ $signedJwt = SignedJwt::createFromString($tokenString);
> **Note:** Tokens created in this way are not verified. You must pass them through `JwtVerifier::verify()` to verify them.
<h4 id="jwt-ids">JWT Ids</h4>

Any time you create a new JWT payload, it's automatically assigned a unique JWT Id (also known as a JTI). This Id is a combination of the JWT's claims and a random string. You can grab the Id like so:

```php
Expand Down
13 changes: 13 additions & 0 deletions authorization.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
1. [Checking Permissions](#checking-permissions)

<h2 id="introduction">Introduction</h2>

The authorization library simplifies how you check if a user should have access to resources. It provides many models that are common to most authorization schemes. It is meant to be used in conjunction with standards like OAuth2. With community help, it is possible for full OAuth2 support to eventually be provided out of the box.

<h2 id="roles">Roles</h2>

A role is a way of describing what a subject is. Usually, roles, such as "editor" or "administrator" also have permissions. Rather than having to assign a permission to each subject, you can group those users by roles, and then assign a permission to that role.

To use Opulence's authorization library, you must implement:
Expand All @@ -40,16 +42,19 @@ $roles = new Roles($roleMembershipRepository, $roleRepository);
```

<h4 id="creating-roles">Creating Roles</h4>

```php
$roles->createRole('new-role'); // Returns the new Role object
```

<h4 id="deleting-roles">Deleting Roles</h4>

```php
$roles->deleteRole('role-to-delete');
```

<h4 id="assigning-roles">Assigning Roles</h4>

```php
// The Id of the subject that is getting this role
$subjectId = 123;
Expand All @@ -58,6 +63,7 @@ $roles->assignRoles($subjectId, 'new-role');
```

<h4 id="revoking-roles">Revoking Roles</h4>

You can revoke a single role from a subject:
```php
// The Id of the subject whose role is being revoked
Expand All @@ -74,11 +80,13 @@ $roles->removeAllRolesFromSubject($subjectId);
```

<h4 id="getting-subjects-by-role">Getting Subjects by Role</h4>

```php
$subjectIdsWithRole = $roles->getSubjectIdsWithRole('search-role');
```

<h2 id="permissions">Permissions</h2>

Permissions are privileges granted to roles. Opulence provides `Opulence\Authorization\Permissions\PermissionRegistry` as a class to store the mapping of roles to permissions.

```php
Expand All @@ -88,11 +96,13 @@ $registry = new PermissionRegistry();
```

<h4 id="registering-permission-with-role">Registering a Permission with a Role</h4>

```php
$registry->registerRoles('create-posts', ['editor', 'author']);
```

<h4 id="registering-a-callback">Registering a Callback</h4>

If your permission logic is a bit more involved, you can register a callback to evaluate if a subject has a permission:

```php
Expand All @@ -108,6 +118,7 @@ $registry->registerCallback('create-users', $callback);
```

<h4 id="registering-overriding-callback">Registering an Overriding Callback</h4>

If you would like to short-circuit the permission checks, you may register what's called an "overriding callback". This is most useful in the case of admins who have access to all permissions.

```php
Expand All @@ -119,6 +130,7 @@ $registry->registerOverridingCallback($callback);
```

<h2 id="authority">Authority</h2>

`Opulence\Authorization\Authority` provides the ability to check if a user has certain permissions.

```php
Expand All @@ -138,6 +150,7 @@ $authority = new Authority(
```

<h4 id="checking-permissions">Checking Permissions</h4>

```php
if ($authority->can('create-posts')) {
$postRepository->save();
Expand Down
7 changes: 7 additions & 0 deletions bootstrappers.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
5. [Config Values](#config-values)

<h2 id="introduction">Introduction</h2>

Most applications need to do some configuration before starting. For example, they might need to setup a database connection, configure which view engine to use, or assign the authentication scheme to use. Because Opulence uses [dependency injection](ioc-container) heavily, it's important that you set your bindings in the IoC container. Bootstrappers are the place to do this.

Bootstrappers are loaded before the request is handled. Typically, they register bindings to the IoC container, but they can also perform any necessary logic once all of the bindings are registered or before the application is shut down. Bootstrappers extend `Opulence\Ioc\Bootstrappers\Bootstrapper`. Their constructors are empty.

<h2 id="registering-bindings">Registering Bindings</h2>

Before you can start using your application, your IoC container needs some bindings to be registered. This is where `Bootstrapper::registerBindings()` comes in handy. Anything that needs to be bound to the IoC container should be done here. Once the application is started, all bootstrappers' bindings are registered.

```php
Expand All @@ -32,6 +34,7 @@ class MyBootstrapper extends Bootstrapper
```

<h2 id="lazy-bootstrappers">Lazy Bootstrappers</h2>

It's not very efficient to create, register bindings, run, and shut down every bootstrapper in your application when they're not all needed. Sometimes, you may only like a bootstrapper to be registered/run/shut down if its bindings are required. This is the purpose of **lazy bootstrappers**. In Opulence, you can designate a bootstrapper to be lazy-loaded by making it implement `Opulence\Ioc\Bootstrappers\ILazyBootstrapper`, which requires a `getBindings()` method to be defined. This method should return a list of all classes/interfaces bound to the IoC container by that bootstrapper. Let's take a look at an example:

```php
Expand All @@ -58,6 +61,7 @@ class MyBootstrapper extends Bootstrapper implements ILazyBootstrapper
```

<h4 id="targeted-bindings">Targeted Bindings</h4>

If you take advantage of [targeted bindings](dependency-injection#targeted-bindings) in your lazy bootstrapper, you must indicate so in `getBindings()` by denoting targeted bindings in the format `[BoundClass => TargetClass]`. Let's say your repository class looks like this:

```php
Expand Down Expand Up @@ -114,12 +118,15 @@ class MyBootstrapper extends Bootstrapper implements ILazyBootstrapper
`[IDataMapper::class => PostRepo::class]` in `getBindings()` lets the bootstrapper know that `IDataMapper` is bound for `PostRepo`. When the bootstrapper's bindings are registered, `IDataMapper` will be bound to `MyDataMapper` whenever `PostRepo` is instantiated by the dependency injection container.

<h4 id="bootstrapper-caching">Caching</h4>

Opulence automatically caches data about its lazy and eager (ie not lazy) bootstrappers. This way, it doesn't have to instantiate each bootstrapper to determine which kind it is. It also remembers which classes are bound by which bootstrappers. If you add/remove/modify any bootstrappers, you must run [`php apex framework:flushcache`](console-basics#frameworkflushcache) command in the console to flush this cache.

<h2 id="environment-variables">Environment Variables</h2>

Sometimes, your bootstrappers need access to environment variables. To access them, simply use PHP's built-in `getenv()` function.

<h2 id="config-values">Config Values</h2>

If you're using the <a href="https://github.com/opulencephp/Project" target="_blank">skeleton project</a> and you need to access config values such as the path to a particular directory, use `Opulence\Framework\Configuration\Config::get($category, $name)`. `$category` refers to the category of the config value, eg "paths" or "routing". The `$name` refers to the actual name of the config value.

> **Note:** `Config` is only meant to be used within bootstrappers as a means to grab config values for your application. It's good practice to never use them outside of bootstrappers.
5 changes: 5 additions & 0 deletions cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
5. [Redis Bridge](#redis-bridge)

<h2 id="introduction">Introduction</h2>

Cache is in-memory storage for frequently-accessed data. Data in cache is commonly short-lived, but it can be persisted for long periods of time. There are many caching libraries out there, such as Redis and Memcached, which offer tons of great features. However, sometimes all your application needs is basic caching functions like:

1. `decrement($key, $by = 1)`
Expand All @@ -21,6 +22,7 @@ Cache is in-memory storage for frequently-accessed data. Data in cache is commo
In this case, you can use a cache **bridge** to provide a simple wrapper around your favorite cache libraries. Opulence supplies the `Opulence\Cache\ICacheBridge` interface with the above methods as well as some bridges to the most popular cache libraries.

<h2 id="array-bridge">Array Bridge</h2>

`Opulence\Cache\ArrayBridge` provides a simple cache bridge most useful for running tests.

```php
Expand All @@ -30,6 +32,7 @@ $arrayBridge = new ArrayBridge();
```

<h2 id="file-bridge">File Bridge</h2>

`Opulence\Cache\FileBridge` allows you to easily cache data to plaintext files on your server.

```php
Expand All @@ -39,6 +42,7 @@ $fileBridge = new FileBridge('/path/to/my/cache/files');
```

<h2 id="memcached-bridge">Memcached Bridge</h2>

`Opulence\Cache\MemcachedBridge` acts as a simple wrapper around Memcached.

```php
Expand Down Expand Up @@ -69,6 +73,7 @@ If you need the underlying Memcached instance to do anything beyond what the bri
> **Note:** [Read more information](memcached) about Opulence's Memcached extension.
<h2 id="redis-bridge">Redis Bridge</h2>

`Opulence\Cache\RedisBridge` is a simple bridge to Redis.

```php
Expand Down
Loading

0 comments on commit e20b5c8

Please sign in to comment.