First public commit
This commit is contained in:
2019-12-20 11:00:00 +03:00
commit a3aaac1d0e
7 changed files with 384 additions and 0 deletions

5
.gitignore vendored Executable file
View File

@@ -0,0 +1,5 @@
/build
/vendor
composer.phar
composer.lock
.DS_Store

21
LICENSE Executable file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 Alexander Vasilyev <a.vasilyev@1sept.ru>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

20
README.md Executable file
View File

@@ -0,0 +1,20 @@
# September First OAuth2 client provider
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
This package provides [September First](https://api.1sept.ru) integration for [OAuth2 Client](https://github.com/thephpleague/oauth2-client) by the League.
## Installation
```sh
composer require 1sept/oauth2-1sept
```
## Usage
```php
$provider = new Sept\OAuth2\Client\Provider\SeptemberFirst([
'clientId' => 'client_id',
'clientSecret' => 'secret',
'redirectUri' => 'https://example.org/oauth-endpoint',
]);
```

41
composer.json Executable file
View File

@@ -0,0 +1,41 @@
{
"name": "1sept/oauth2-1sept",
"description": "September First OAuth 2.0 Client Provider for The PHP League OAuth2-Client",
"license": "MIT",
"authors": [
{
"name": "Alexander Vasilyev",
"email": "a.vasilyev@1sept.ru"
}
],
"keywords": [
"oauth",
"oauth2",
"client",
"authorization",
"authorisation",
"1sept"
],
"require": {
"php": "^5.6|^7.0",
"league/oauth2-client": "^2.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"autoload": {
"psr-4": {
"Sept\\OAuth2\\Client\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Sept\\OAuth2\\Client\\Test\\": "test/src/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
}
}

37
phpunit.xml Executable file
View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<logging>
<log type="coverage-html"
target="./build/coverage/html"
charset="UTF-8"
highlight="false"
lowUpperBound="35"
highLowerBound="70"/>
<log type="coverage-clover"
target="./build/coverage/log/coverage.xml"/>
</logging>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./test/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./</directory>
<exclude>
<directory suffix=".php">./vendor</directory>
<directory suffix=".php">./test</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

@@ -0,0 +1,66 @@
<?php
namespace Sept\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Psr\Http\Message\ResponseInterface;
class SeptemberFirstProvider extends AbstractProvider
{
use BearerAuthorizationTrait;
/**
* Личный кабинет Первое сентября
*
* @var string
*/
const AUTH_BASE = 'https://my.1sept.ru';
/**
* API Первое сентября
*
* @var string
*/
const API_BASE = 'https://api.1sept.ru';
const API_VERSION = '2.0';
public function getBaseAuthorizationUrl(): string
{
return static::AUTH_BASE.'/oauth/authorize';
}
public function getBaseAccessTokenUrl(array $params): string
{
return static::API_BASE.'/oauth/access_token';
}
public function getResourceOwnerDetailsUrl(AccessToken $token): string
{
return static::API_BASE.'/'.static::API_VERSION.'/userinfo';
}
public function getDefaultScopes(): array
{
return ['basic'];
}
protected function getScopeSeparator(): string
{
return ' ';
}
protected function checkResponse(ResponseInterface $response, $data)
{
if (!empty($data['error'])) {
throw new IdentityProviderException($data['error'].': '.$data['message'], null, $response);
}
}
protected function createResourceOwner(array $response, AccessToken $token): SeptemberFirstUser
{
return new SeptemberFirstUser($response);
}
}

View File

@@ -0,0 +1,194 @@
<?php
namespace Sept\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
class SeptemberFirstUser implements ResourceOwnerInterface
{
/**
* Массив с данными о пользователе
*/
protected $data;
/**
* Конструктор
*/
public function __construct(array $response)
{
$this->data = $response;
}
/**
* Значение массива (многомерного)
*
* @param string $key Ключ поля (например: `email` или `name.first` — вложенность оформляется точкой)
* @return mixed|null
*/
public static function getFieldFromArray(string $key, ?array $array)
{
if (strpos($key, '.')) { // key.subKey.subSubKey
list ($key, $subKey) = explode('.', $key, 2);
return isset($array[$key]) ? static::getFieldFromArray($subKey, $array[$key]) : null;
}
return isset($array[$key]) ? $array[$key] : null;
}
/**
* Элемент массива данных о пользователе
*
* @param string $key Ключ поля (например: email или name.first — вложенность оформляется точкой)
* @return mixed|null
*/
protected function getField(string $key)
{
return static::getFieldFromArray($key, $this->data);
}
/**
* Данные о пользователе в виде массива
*
* @return array
*/
public function toArray()
{
return $this->data;
}
/**
* ID пользователя
*/
public function getId(): ?string
{
return $this->getField('id');
}
/**
* {@inheritdoc}
*/
public function getLastName(): ?string
{
return $this->getField('personal_name.surname');
}
/**
* {@inheritdoc}
*/
public function getFirstName(): ?string
{
return $this->getField('personal_name.name');
}
/**
* {@inheritdoc}
*/
public function getMiddleName(): ?string
{
return $this->getField('personal_name.patronymic');
}
/**
* Девичья фамилия пользователя (только для женского пола)
*
* @return string|null
*/
public function getMaidenName(): ?string
{
return null;
}
/**
* {@inheritdoc}
*/
public function getDisplayName(): ?string
{
return $this->getField('display_name');
}
/**
* {@inheritdoc}
*/
public function getSex(): ?string
{
return $this->getField('sex');
}
/**
* {@inheritdoc}
*/
public function getEmail(): ?string
{
return $this->getField('email');
}
/**
* {@inheritdoc}
*/
public function getBirthday(): ?\DateTime
{
return !empty($this->data['birthday']) ? new \DateTime($this->data['birthday']) : null;
}
/**
* {@inheritdoc}
*/
public function getAvatarUrl(bool $rejectEmptyAvatar = false): ?string
{
if (empty($this->data['avatar']) or ((!isset($this->data['has_avatar']) or !$this->data['has_avatar']) and $rejectEmptyAvatar)) {
return null;
}
return $this->getField('avatar');
}
/**
* Адрес аватарки 50x50
*
* @param bool $rejectEmptyAvatar Если true, то пустые аватарки (заглушки) не отдаются
* @return string|null
*/
public function getAvatar50Url(bool $rejectEmptyAvatar = false): ?string
{
return $this->getAvatarUrl($rejectEmptyAvatar);
}
/**
* {@inheritdoc}
*/
public function getProfileUrl(): ?string
{
return $this->getField('profile_url');
}
/**
* Номер телефона
*
* @return string|null
*/
public function getPhone(): ?string
{
return null;
}
/**
* Локаль
*
* @return string|null
*/
public function getLocale(): ?string
{
return null;
}
/**
* Имя временной зоны (от -24 до 24)
* @example Europe/Moscow
*
* @return string|null
*/
public function getTimezone(): ?string
{
return $this->getField('timezone');
}
}