Merge branch 'refactor_structure'

This commit is contained in:
ErickSkrauch 2016-10-02 01:21:12 +03:00
commit 5d1dab6e92
95 changed files with 848 additions and 1054 deletions

View File

@ -3,11 +3,9 @@
# vendor будет заполнен уже внутри контейнера
vendor
# node_modules для этого контейнера не нужны
# Всё, что динамично на фронте
frontend/node_modules
# Все -local файлы
*/config/*-local.php
frontend/dist
# Все временные файлы
*/runtime

26
.env
View File

@ -1,2 +1,26 @@
XDEBUG_CONFIG=remote_host=192.168.99.1
# Основные параметры
YII_DEBUG=true
YII_ENV=dev
JWT_USER_SECRET=edee109cad8b323d6d9edbcf406d945a989af6b6d251e4953a48df756695963a
# Web
VIRTUAL_HOST=account.ely.by.local,authserver.ely.by.local
AUTHSERVER_HOST=authserver.ely.by.local
# LETSENCRYPT_HOST=account.ely.by
# LETSENCRYPT_EMAIL=erickskrauch@ely.by
# MySQL
MYSQL_ALLOW_EMPTY_PASSWORD=yes
MYSQL_ROOT_PASSWORD=
MYSQL_DATABASE=ely_accounts
MYSQL_USER=ely_accounts_user
MYSQL_PASSWORD=ely_accounts_password
# RabbitMQ
RABBITMQ_DEFAULT_USER=ely-accounts-app
RABBITMQ_DEFAULT_PASS=ely-accounts-app-password
RABBITMQ_DEFAULT_VHOST=/ely.by
# Конфигурация для Dev.
XDEBUG_CONFIG=remote_host=10.254.254.254
PHP_IDE_CONFIG=serverName=docker

26
.env-dist Normal file
View File

@ -0,0 +1,26 @@
# Основные параметры
YII_DEBUG=true
YII_ENV=dev
JWT_USER_SECRET=
# Web
VIRTUAL_HOST=account.ely.by,authserver.ely.by
AUTHSERVER_HOST=authserver.ely.by
# LETSENCRYPT_HOST=account.ely.by
# LETSENCRYPT_EMAIL=erickskrauch@ely.by
# MySQL
MYSQL_ALLOW_EMPTY_PASSWORD=yes
MYSQL_ROOT_PASSWORD=
MYSQL_DATABASE=ely_accounts
MYSQL_USER=ely_accounts_user
MYSQL_PASSWORD=ely_accounts_password
# RabbitMQ
RABBITMQ_DEFAULT_USER=ely-accounts-app
RABBITMQ_DEFAULT_PASS=ely-accounts-app-password
RABBITMQ_DEFAULT_VHOST=/ely.by
# Конфигурация для Dev.
XDEBUG_CONFIG=remote_host=10.254.254.254
PHP_IDE_CONFIG=serverName=docker

37
.gitignore vendored
View File

@ -1,37 +1,22 @@
# yii console command
/yii
# phpstorm project files
.idea
# netbeans project files
nbproject
# zend studio for eclipse project files
.buildpath
.project
.settings
# windows thumbnail cache
Thumbs.db
# composer vendor dir
# Composer
/vendor
# composer itself is not needed
composer.phar
composer.lock
/composer.lock
# Mac DS_Store Files
.DS_Store
# phpunit itself is not needed
phpunit.phar
# local phpunit config
/phpunit.xml
# npm debug
npm-debug*
# Docker override file
docker-compose.override.yml
# Docker и его override файлы
/docker-compose.yml
/docker-compose.override.yml
# Локальный .env
/.env
# id_rsa
/id_rsa

View File

@ -1,8 +1,8 @@
FROM php:7.1-fpm
FROM php:7.0-fpm
ENV PATH $PATH:/root/.composer/vendor/bin
# PHP extensions come first, as they are less likely to change between Yii releases
# Сначала настраиваем всё, что нам нужно на системном уровне
RUN apt-get update \
&& apt-get -y install \
git \
@ -10,45 +10,53 @@ RUN apt-get update \
libicu-dev \
libmcrypt-dev \
zlib1g-dev \
bzip2 \
libbz2-dev \
liblzma-dev \
xz-utils \
openssh-server \
supervisor \
--no-install-recommends \
--force-yes \
# Install PHP extensions
# PHP расширения
&& docker-php-ext-install intl \
&& docker-php-ext-install pdo_mysql \
&& docker-php-ext-install mbstring \
&& docker-php-ext-install mcrypt \
&& docker-php-ext-install zip \
&& docker-php-ext-install bcmath \
&& docker-php-ext-install opcache \
&& apt-get purge -y g++ \
&& apt-get autoremove -y \
&& rm -r /var/lib/apt/lists/* \
# Don't clear our valuable environment vars in PHP
# Отключаем сброс глобальных env переменных внутри PHP
&& echo "\nclear_env = no" >> /usr/local/etc/php-fpm.conf \
# Fix write permissions with shared folders
# Фикс прав на запись для расшаренных папок
&& usermod -u 1000 www-data
# copy-paste from https://github.com/nodejs/docker-node/blob/910443c39c80291f0bf24712d8d94279cf15b7b5/6.5/wheezy/Dockerfile
# Копипаста из https://github.com/nodejs/docker-node/blob/50b56d39a236fd519eda2231757aa2173e270807/5.12/Dockerfile
# gpg keys listed at https://github.com/nodejs/node
RUN set -ex \
&& for key in \
9554F04D7259F04124DE6B476D5A82AC7E37093B \
94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \
0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93 \
FD3A5288F042B6850C66B31F09FE44734EB7990E \
71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \
DD8F2338BAE7501E3DD5AC78C273792F7D83545D \
B9AE9905FFD7803F25714661B63B535A4C206CA9 \
C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \
; do \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \
done
&& for key in \
9554F04D7259F04124DE6B476D5A82AC7E37093B \
94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \
0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93 \
FD3A5288F042B6850C66B31F09FE44734EB7990E \
71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \
DD8F2338BAE7501E3DD5AC78C273792F7D83545D \
B9AE9905FFD7803F25714661B63B535A4C206CA9 \
C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \
; do \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \
done
ENV NPM_CONFIG_LOGLEVEL info
ENV NODE_VERSION 6.5.0
ENV NODE_VERSION 5.12.0
RUN curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.xz" \
&& curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc" \
@ -58,43 +66,84 @@ RUN curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-
&& rm "node-v$NODE_VERSION-linux-x64.tar.xz" SHASUMS256.txt.asc SHASUMS256.txt \
&& ln -s /usr/local/bin/node /usr/local/bin/nodejs
# Поставим xdebug отдельно, т.к. потом его потенциально придётся отсюда убирать
RUN yes | pecl install xdebug \
&& echo "zend_extension=$(find /usr/local/lib/php/extensions/ -name xdebug.so)" > /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.default_enable=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_enable=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_handler=dbgp" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_mode=req" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_autostart=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_port=9000" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_connect_back=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.cli_color=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.var_display_max_depth=10" >> /usr/local/etc/php/conf.d/xdebug.ini
ENV COMPOSER_NO_INTERACTION 1
ENV COMPOSER_ALLOW_SUPERUSER 1
ENV COMPOSER_DISCARD_CHANGES true
# Next composer and global composer package, as their versions may change from time to time
# Composer и его глобальные зависимости
RUN curl -sS https://getcomposer.org/installer | php \
&& mv composer.phar /usr/local/bin/composer.phar \
&& echo '{"github-oauth": {"github.com": "***REMOVED***"}}' > ~/.composer/auth.json \
&& composer.phar global require --no-progress "hirak/prestissimo:>=0.3.1"
&& composer.phar global require --no-progress "hirak/prestissimo:>=0.3.4"
COPY ./docker/php/composer.sh /usr/local/bin/composer
RUN chmod a+x /usr/local/bin/composer
# Конфиг для php
COPY ./docker/php/php.ini /usr/local/etc/php/
# Конфиг для supervisor
COPY ./docker/php/supervisord.conf /etc/supervisord.conf
# wait-for-it
COPY ./docker/wait-for-it.sh /usr/local/bin/wait-for-it
# Наша кавайная точка входа
COPY ./docker/php/entrypoint.sh /usr/local/bin/
RUN chmod a+x /usr/local/bin/composer \
&& chmod a+x /usr/local/bin/entrypoint.sh \
&& chmod a+x /usr/local/bin/wait-for-it \
&& ln -s /usr/local/bin/entrypoint.sh / \
&& mkdir /root/.ssh
COPY id_rsa /root/.ssh
# Включаем поддержку ssh
RUN eval $(ssh-agent -s) \
&& ssh-add /root/.ssh/id_rsa \
&& touch /root/.ssh/known_hosts \
&& ssh-keyscan gitlab.com >> /root/.ssh/known_hosts
WORKDIR /var/www/html
# Custorm php configuration
COPY ./docker/php/php.ini /usr/local/etc/php/
# Копируем composer.json в родительскую директорию, которая не будет синкатся с хостом через
# volume на dev окружении. В entrypoint эта папка будет скопирована обратно.
COPY ./composer.json /var/www/composer.json
# Copy the working dir to the image's web root
# Устанавливаем зависимости PHP
RUN cd .. \
&& composer install --no-interaction --no-suggest --no-dev --optimize-autoloader \
&& cd -
# Устанавливаем зависимости для Node.js
# Делаем это отдельно, чтобы можно было воспользоваться кэшем, если от предыдущего билда
# ничего не менялось в зависимостях
RUN mkdir -p /var/www/frontend
COPY ./frontend/package.json /var/www/frontend/
COPY ./frontend/scripts /var/www/frontend/scripts
COPY ./frontend/webpack-utils /var/www/frontend/webpack-utils
RUN cd ../frontend \
&& npm install \
&& cd -
# Наконец переносим все сорцы внутрь контейнера
COPY . /var/www/html
# The following directories are .dockerignored to not pollute the docker images
# with local logs and published assets from development. So we need to create
# empty dirs and set right permissions inside the container.
RUN mkdir -p api/runtime api/web/assets console/runtime \
&& chown www-data:www-data api/runtime api/web/assets console/runtime
&& chown www-data:www-data api/runtime api/web/assets console/runtime \
# Билдим фронт
&& cd frontend \
&& ln -s /var/www/frontend/node_modules $PWD/node_modules \
&& npm run build \
&& rm node_modules \
# Копируем билд наружу, чтобы его не затёрло volume в dev режиме
&& cp -r ./dist /var/www/dist \
&& cd -
# Expose everything under /var/www (vendor + html)
VOLUME ["/var/www"]
# Экспозим всё под /var/www/html для дальнейшей связки с nginx
VOLUME ["/var/www/html"]
ENTRYPOINT ["entrypoint.sh"]
CMD ["/usr/bin/supervisord", "-n", "-c", "/etc/supervisord.conf"]

162
Dockerfile-dev Normal file
View File

@ -0,0 +1,162 @@
FROM php:7.0-fpm
ENV PATH $PATH:/root/.composer/vendor/bin
# Сначала настраиваем всё, что нам нужно на системном уровне
RUN apt-get update \
&& apt-get -y install \
git \
g++ \
libicu-dev \
libmcrypt-dev \
zlib1g-dev \
bzip2 \
libbz2-dev \
liblzma-dev \
xz-utils \
openssh-server \
supervisor \
--no-install-recommends \
--force-yes \
# PHP расширения
&& docker-php-ext-install intl \
&& docker-php-ext-install pdo_mysql \
&& docker-php-ext-install mbstring \
&& docker-php-ext-install mcrypt \
&& docker-php-ext-install zip \
&& docker-php-ext-install bcmath \
&& docker-php-ext-install opcache \
&& apt-get purge -y g++ \
&& apt-get autoremove -y \
&& rm -r /var/lib/apt/lists/* \
# Отключаем сброс глобальных env переменных внутри PHP
&& echo "\nclear_env = no" >> /usr/local/etc/php-fpm.conf \
# Фикс прав на запись для расшаренных папок
&& usermod -u 1000 www-data
# Копипаста из https://github.com/nodejs/docker-node/blob/50b56d39a236fd519eda2231757aa2173e270807/5.12/Dockerfile
# gpg keys listed at https://github.com/nodejs/node
RUN set -ex \
&& for key in \
9554F04D7259F04124DE6B476D5A82AC7E37093B \
94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \
0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93 \
FD3A5288F042B6850C66B31F09FE44734EB7990E \
71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \
DD8F2338BAE7501E3DD5AC78C273792F7D83545D \
B9AE9905FFD7803F25714661B63B535A4C206CA9 \
C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \
; do \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \
done
ENV NPM_CONFIG_LOGLEVEL info
ENV NODE_VERSION 5.12.0
RUN curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.xz" \
&& curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc" \
&& gpg --batch --decrypt --output SHASUMS256.txt SHASUMS256.txt.asc \
&& grep " node-v$NODE_VERSION-linux-x64.tar.xz\$" SHASUMS256.txt | sha256sum -c - \
&& tar -xJf "node-v$NODE_VERSION-linux-x64.tar.xz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-x64.tar.xz" SHASUMS256.txt.asc SHASUMS256.txt \
&& ln -s /usr/local/bin/node /usr/local/bin/nodejs
# Поставим xdebug отдельно, т.к. потом его потенциально придётся отсюда убирать
RUN yes | pecl install xdebug \
&& echo "zend_extension=$(find /usr/local/lib/php/extensions/ -name xdebug.so)" > /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.default_enable=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_enable=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_handler=dbgp" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_mode=req" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_autostart=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_port=9000" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.remote_connect_back=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.cli_color=1" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.var_display_max_depth=10" >> /usr/local/etc/php/conf.d/xdebug.ini
ENV COMPOSER_NO_INTERACTION 1
ENV COMPOSER_ALLOW_SUPERUSER 1
ENV COMPOSER_DISCARD_CHANGES true
# Composer и его глобальные зависимости
RUN curl -sS https://getcomposer.org/installer | php \
&& mv composer.phar /usr/local/bin/composer.phar \
&& echo '{"github-oauth": {"github.com": "***REMOVED***"}}' > ~/.composer/auth.json \
&& composer.phar global require --no-progress "hirak/prestissimo:>=0.3.4"
COPY ./docker/php/composer.sh /usr/local/bin/composer
# Конфиг для php
COPY ./docker/php/php.ini /usr/local/etc/php/
# Конфиг для supervisor
COPY ./docker/php/supervisord.conf /etc/supervisord.conf
# wait-for-it
COPY ./docker/wait-for-it.sh /usr/local/bin/wait-for-it
# Наша кавайная точка входа
COPY ./docker/php/entrypoint.sh /usr/local/bin/
RUN chmod a+x /usr/local/bin/composer \
&& chmod a+x /usr/local/bin/entrypoint.sh \
&& chmod a+x /usr/local/bin/wait-for-it \
&& ln -s /usr/local/bin/entrypoint.sh / \
&& mkdir /root/.ssh
COPY id_rsa /root/.ssh
# Включаем поддержку ssh
RUN eval $(ssh-agent -s) \
&& ssh-add /root/.ssh/id_rsa \
&& touch /root/.ssh/known_hosts \
&& ssh-keyscan gitlab.com >> /root/.ssh/known_hosts
WORKDIR /var/www/html
# Копируем composer.json в родительскую директорию, которая не будет синкатся с хостом через
# volume на dev окружении. В entrypoint эта папка будет скопирована обратно.
COPY ./composer.json /var/www/composer.json
# Устанавливаем зависимости PHP
RUN cd .. \
&& composer install --no-interaction --no-suggest \
&& cd -
# Устанавливаем зависимости для Node.js
# Делаем это отдельно, чтобы можно было воспользоваться кэшем, если от предыдущего билда
# ничего не менялось в зависимостях
RUN mkdir -p /var/www/frontend
COPY ./frontend/package.json /var/www/frontend/
COPY ./frontend/scripts /var/www/frontend/scripts
COPY ./frontend/webpack-utils /var/www/frontend/webpack-utils
RUN cd ../frontend \
&& npm install \
&& cd -
# Наконец переносим все сорцы внутрь контейнера
COPY . /var/www/html
RUN mkdir -p api/runtime api/web/assets console/runtime \
&& chown www-data:www-data api/runtime api/web/assets console/runtime \
# Билдим фронт
&& cd frontend \
&& ln -s /var/www/frontend/node_modules $PWD/node_modules \
&& npm run build \
&& rm node_modules \
# Копируем билд наружу, чтобы его не затёрло volume в dev режиме
&& cp -r ./dist /var/www/dist \
&& cd -
# Экспозим всё под /var/www/html для дальнейшей связки с nginx
VOLUME ["/var/www/html"]
ENTRYPOINT ["entrypoint.sh"]
CMD ["/usr/bin/supervisord", "-n", "-c", "/etc/supervisord.conf"]

View File

@ -1,4 +1,4 @@
# Account Ely.by
# Accounts Ely.by
## Развёртывание dev
@ -6,61 +6,49 @@
[docker](https://docs.docker.com/engine/installation/) и его
[docker-compose](https://docs.docker.com/compose/install/).
Сливаем репозиторий:
Кроме того, нужно установить, настроить и запустить [nginx-proxy](https://gitlab.com/elyby/nginx-proxy)
контейнер. Это делается один раз в рамках системы и в дальнейшем используется и для других проектов.
За тем сливаем репозиторий:
```sh
git clone git@bitbucket.org:ErickSkrauch/ely.by-account.git account.ely.by.local
git clone git@gitlab.com:elyby/account.git account.ely.by
cd account.ely.by.local
```
Выполняем первый запуск контейнеров:
Далее нужно создать `.env`, `docker-compose.yml` и `id_rsa` файлы:
```sh
cp .env-dist .env
cp docker-compose.dev.yml docker-compose.yml
cp ~/.ssh/id_rsa id_rsa # Использовать ссылку нельзя
```
Касательно файла id_rsa: часть зависимостей находятся в наших приватных репозиториях, получить
доступ куда можно только в том случае, если в контейнере окажется ключ, который имеет доступ к этим
репозиториям.
Все вышеперечисленные файла находятся под gitignore, так что с полученными файлами можно произвести
все необходимые манипуляции под конкретный кейс использования. **В файле `.env` обязательно следует
задать `JWT_USER_SECRET`, иначе авторизация на бекенде не заработает.**
После этого просто выполняем старт всех контейнеров:
```sh
docker-compose up -d
```
Далее нужно влезть в работающие контейнеры и сделать что-нибудь, что их настроит.
Они автоматически сбилдятся и начнут свою работу.
### Как влезть в работающий контейнер
Сперва, с помощью команды `docker ps` мы увидим все запущенные контейнеры. Нас интересуют значения из первой колонки
CONTAINER ID. Узнать, чему они соответствуют можно прочитав название IMAGE из 2 колонки. Чтобы выполнить команду
внутри работабщего контейнера, нужно выполнить:
Сперва, с помощью команды `docker ps` мы увидим все запущенные контейнеры. Нас интересуют значения
из первой колонки CONTAINER ID или NAMES. Узнать, чему они соответствуют можно прочитав название IMAGE
из 2 колонки. Чтобы выполнить команду внутри работабщего контейнера, нужно выполнить:
```
docker exec -it a7c267b27f49 /bin/bash
docker exec -it accountelyby_app_1 bash
```
Где `a7c267b27f49` - одно из значений из первой колонки. Для выхода из контейнера используем `exit`.
-------------------------
Так вот, нам нужно выполнить ряд команд. Здесь и далее я буду писать имена контейнеров в их соответствии с compose
файлом, но в реалиях их нужно будет заменить на реальные значения:
```sh
# Настройка php контейнера
docker exec -it app php init --env=Docker
docker exec -it app php composer install
docker exec -it app php ./yii migrate --interactive=0
# Настройка node контейнера
docker exec -it node-dev-server npm i
docker exec -it node-dev-server npm --prefix ./webpack i ./webpack
docker exec -it node-dev-server npm --prefix ./scripts i ./scripts
# Настройка rabbitmq контейнера
docker exec -it rabbitmq /init.sh
```
После этого перезапускаем все контейнеры командой:
```sh
docker-compose restart
```
## Тестирование php бэкэнда
```sh
./tests/run-tests.sh
```
Где `accountelyby_app_1` - одно из значений CONTAINER ID или NAMES. Для выхода из контейнера
используем `exit`.

View File

@ -7,7 +7,6 @@ use Emarref\Jwt\Algorithm\AlgorithmInterface;
use Emarref\Jwt\Algorithm\Hs256;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Encryption\Factory;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Token;
@ -122,7 +121,7 @@ class Component extends YiiUserComponent {
$jwt = new Jwt();
$token = $jwt->deserialize($jwtString);
$context = new VerificationContext(Factory::create($this->getAlgorithm()));
$context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm()));
$context->setAudience($hostInfo);
$context->setIssuer($hostInfo);
$jwt->verify($token, $context);

View File

@ -1,2 +1 @@
main-local.php
params-local.php

19
api/config/config-dev.php Normal file
View File

@ -0,0 +1,19 @@
<?php
return [
'bootstrap' => ['debug', 'gii'],
'components' => [
'reCaptcha' => [
'public' => '6LfwqCYTAAAAAJlaJpqCdzESCjAXUC81Ca6jBHR7',
'secret' => '6LfwqCYTAAAAAFPjHmgwmnjSMFeAOJh7Lk5xxDMC',
],
],
'modules' => [
'debug' => [
'class' => yii\debug\Module::class,
'allowedIPs' => ['*'],
],
'gii' => [
'class' => yii\gii\Module::class,
],
],
];

View File

@ -1,9 +1,7 @@
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
require(__DIR__ . '/params.php')
);
return [
@ -14,17 +12,17 @@ return [
'params' => $params,
'components' => [
'user' => [
'class' => \api\components\User\Component::class,
'secret' => $params['userSecret'],
'class' => api\components\User\Component::class,
'secret' => getenv('JWT_USER_SECRET'),
],
'apiUser' => [
'class' => \api\components\ApiUser\Component::class,
'class' => api\components\ApiUser\Component::class,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => \yii\log\FileTarget::class,
'class' => yii\log\FileTarget::class,
'levels' => ['error', 'warning'],
'except' => [
'legacy-authserver',
@ -34,13 +32,13 @@ return [
],
],
[
'class' => \yii\log\FileTarget::class,
'class' => yii\log\FileTarget::class,
'levels' => ['error', 'info'],
'categories' => ['legacy-authserver'],
'logFile' => '@runtime/logs/authserver.log',
],
[
'class' => \yii\log\FileTarget::class,
'class' => yii\log\FileTarget::class,
'levels' => ['error', 'info'],
'categories' => ['session'],
'logFile' => '@runtime/logs/session.log',
@ -56,26 +54,26 @@ return [
'rules' => require __DIR__ . '/routes.php',
],
'reCaptcha' => [
'class' => \api\components\ReCaptcha\Component::class,
'class' => api\components\ReCaptcha\Component::class,
],
'response' => [
'format' => \yii\web\Response::FORMAT_JSON,
'format' => yii\web\Response::FORMAT_JSON,
],
'oauth' => [
'class' => \common\components\oauth\Component::class,
'class' => common\components\oauth\Component::class,
'grantTypes' => ['authorization_code'],
],
'errorHandler' => [
'class' => \api\components\ErrorHandler::class,
'class' => api\components\ErrorHandler::class,
],
],
'modules' => [
'authserver' => [
'class' => \api\modules\authserver\Module::class,
'baseDomain' => $params['authserverDomain'],
'class' => api\modules\authserver\Module::class,
'baseDomain' => getenv('AUTHSERVER_HOST'),
],
'session' => [
'class' => \api\modules\session\Module::class,
'class' => api\modules\session\Module::class,
],
],
];

View File

@ -1,4 +1,4 @@
<?php
return [
'adminEmail' => 'admin@example.com',
'authserverHost' => getenv('AUTHSERVER_HOST'),
];

View File

@ -25,6 +25,7 @@ class SessionController extends ApiController {
$behaviors['rateLimiting'] = [
'class' => RateLimiter::class,
'only' => ['has-joined', 'has-joined-legacy'],
'authserverDomain' => Yii::$app->params['authserverHost'],
];
return $behaviors;

View File

@ -18,10 +18,6 @@ class RateLimiter extends \yii\filters\RateLimiter {
public function init() {
parent::init();
if ($this->authserverDomain === null) {
$this->authserverDomain = Yii::$app->params['authserverDomain'] ?? null;
}
if ($this->authserverDomain === null) {
throw new InvalidConfigException('authserverDomain param is required');
}
@ -45,7 +41,7 @@ class RateLimiter extends \yii\filters\RateLimiter {
* @inheritdoc
*/
public function checkRateLimit($user, $request, $response, $action) {
if ($request->getHostInfo() === $this->authserverDomain) {
if (parse_url($request->getHostInfo(), PHP_URL_HOST) === $this->authserverDomain) {
return;
}

2
api/web/.gitignore vendored
View File

@ -1,2 +0,0 @@
/index.php
/index-test.php

Binary file not shown.

Before

Width:  |  Height:  |  Size: 318 B

14
api/web/index.php Normal file
View File

@ -0,0 +1,14 @@
<?php
require __DIR__ . '/../../vendor/autoload.php';
defined('YII_DEBUG') or define('YII_DEBUG', (boolean)getenv('YII_DEBUG'));
defined('YII_ENV') or define('YII_ENV', getenv('YII_ENV'));
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
require __DIR__ . '/../config/bootstrap.php';
$config = \common\config\ConfigLoader::load('api');
$application = new yii\web\Application($config);
$application->run();

View File

@ -1,2 +1 @@
main-local.php
params-local.php
config-local.php

View File

@ -0,0 +1,65 @@
<?php
namespace common\config;
use yii\helpers\ArrayHelper;
class ConfigLoader {
/*
* TODO: В PHP 7.1 следует сделать её protected
*/
const ROOT_PATH = __DIR__ . '/../..';
private $application;
public function __construct(string $application) {
$this->application = $application;
}
public function getEnvironment() : string {
return YII_ENV;
}
public function getConfig() : array {
$toMerge = [
require __DIR__ . '/config.php',
];
// Общие окружение-зависимые настройки
$path = __DIR__ . '/config-' . YII_ENV . '.php';
if (file_exists($path)) {
$toMerge[] = require $path;
}
// Общие локальные настройки
$path = __DIR__ . '/config-local.php';
if (file_exists($path)) {
$toMerge[] = require $path;
}
// Настройки конкретного приложения
$path = self::ROOT_PATH . '/' . $this->application . '/config/config.php';
if (file_exists($path)) {
$toMerge[] = require $path;
}
// Настройки конкретного приложения для действующего окружения
$path = self::ROOT_PATH . '/' . $this->application . '/config/config-' . YII_ENV . '.php';
if (file_exists($path)) {
$toMerge[] = require $path;
}
// Локальные настройки конкретного приложения
$path = self::ROOT_PATH . '/' . $this->application . '/config/config-local.php';
if (file_exists($path)) {
$toMerge[] = require $path;
}
return ArrayHelper::merge(...$toMerge);
}
public static function load(string $application) : array {
return (new static($application))->getConfig();
}
}

View File

@ -0,0 +1,8 @@
<?php
return [
'components' => [
'mailer' => [
'useFileTransport' => true,
],
],
];

View File

@ -8,6 +8,9 @@ return [
],
'db' => [
'class' => yii\db\Connection::class,
'dsn' => 'mysql:host=db;dbname=' . getenv('MYSQL_DATABASE'),
'username' => getenv('MYSQL_USER'),
'password' => getenv('MYSQL_PASSWORD'),
'charset' => 'utf8',
],
'mailer' => [
@ -19,12 +22,21 @@ return [
],
'redis' => [
'class' => yii\redis\Connection::class,
'hostname' => 'redis',
'password' => null,
'port' => 6379,
'database' => 0,
],
'amqp' => [
'class' => \common\components\RabbitMQ\Component::class,
'class' => common\components\RabbitMQ\Component::class,
'host' => 'rabbitmq',
'port' => 5672,
'user' => getenv('RABBITMQ_DEFAULT_USER'),
'password' => getenv('RABBITMQ_DEFAULT_PASS'),
'vhost' => getenv('RABBITMQ_DEFAULT_VHOST'),
],
'guzzle' => [
'class' => \GuzzleHttp\Client::class,
'class' => GuzzleHttp\Client::class,
],
],
'aliases' => [

View File

@ -1,6 +1,5 @@
<?php
return [
'adminEmail' => 'admin@example.com',
'supportEmail' => 'support@example.com',
'user.passwordResetTokenExpire' => 3600,
'fromEmail' => 'account@ely.by',
'supportEmail' => 'support@ely.by',
];

View File

@ -25,7 +25,7 @@
"ely/yii2-tempmail-validator": "~1.0.0",
"emarref/jwt": "~1.0.3",
"ely/amqp-controller": "^0.1.0",
"ely/email-renderer": "dev-master#10e77d7a60403e87ca6e8c7d9e62a36fc5e08565"
"ely/email-renderer": "dev-master#4a751652b5a325d44d3bc79a464dda9232486cbc"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
@ -33,10 +33,11 @@
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"flow/jsonpath": "^0.3.1",
"codeception/codeception": "~2.1.10",
"codeception/codeception": "~2.2.4",
"codeception/specify": "*",
"codeception/verify": "*",
"phploc/phploc": "^3.0.1"
"phploc/phploc": "^3.0.1",
"predis/predis": "^1.0"
},
"config": {
"process-timeout": 1800

View File

@ -1,2 +1 @@
main-local.php
params-local.php

View File

@ -1,21 +1,20 @@
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
require(__DIR__ . '/params.php')
);
return [
'id' => 'app-console',
'id' => 'accounts-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'params' => $params,
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'class' => yii\log\FileTarget::class,
'levels' => ['error', 'warning'],
],
],
@ -23,9 +22,8 @@ return [
],
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'class' => yii\console\controllers\MigrateController::class,
'templateFile' => '@console/views/migration.php',
],
],
'params' => $params,
];

View File

@ -1,4 +1,3 @@
<?php
return [
'adminEmail' => 'admin@example.com',
];

2
data/mysql/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
data/redis/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

74
docker-compose.dev.yml Normal file
View File

@ -0,0 +1,74 @@
version: '2'
services:
app:
build:
dockerfile: Dockerfile-dev
context: .
depends_on:
- db
- redis
- rabbitmq
volumes:
- ./:/var/www/html/
env_file: .env
web:
build: ./docker/nginx
volumes_from:
- app
links:
- app:php
env_file: .env
networks:
- default
- nginx-proxy
db:
build: ./docker/mariadb
env_file: .env
volumes:
- ./data/mysql:/var/lib/mysql
redis:
image: redis:3.0-alpine
volumes:
- ./data/redis:/data
rabbitmq:
image: rabbitmq:3.6-management
env_file: .env
environment:
- VIRTUAL_HOST=rabbitmq.account.ely.by.local
- VIRTUAL_PORT=15672
networks:
- default
- nginx-proxy
phpmyadmin:
build: ./docker/phpmyadmin
environment:
- PMA_ARBITRARY=1
- PMA_USER=root
- PMA_PASSWORD=
- VIRTUAL_HOST=pma.account.ely.by.local
depends_on:
- db
networks:
- default
- nginx-proxy
# Эта штука работает дико медленно, грузит процессор и т.д. и т.п.
# Раскоментировать только в случае лютой надобности
#node-dev-server:
# build: ./frontend
# ports:
# - "8080:8080"
# volumes:
# - ./frontend/:/usr/src/app/
# environment:
# DOCKERIZED: "true"
networks:
nginx-proxy:
external:
name: nginx-proxy

40
docker-compose.prod.yml Normal file
View File

@ -0,0 +1,40 @@
version: '2'
services:
app:
build: .
depends_on:
- db
- redis
- rabbitmq
env_file: .env
web:
build: ./docker/nginx
volumes_from:
- app
links:
- app:php
env_file: .env
networks:
- default
- nginx-proxy
db:
build: ./docker/mariadb
env_file: .env
volumes:
- ./data/mysql:/var/lib/mysql
redis:
image: redis:3.0-alpine
volumes:
- ./data/redis:/data
rabbitmq:
image: rabbitmq:3.6
env_file: .env
networks:
nginx-proxy:
external:
name: nginx-proxy

View File

@ -1,66 +1,48 @@
version: '2'
services:
app:
build: .
links:
build:
dockerfile: Dockerfile-dev
context: .
depends_on:
- db
- redis
- rabbitmq
depends_on:
- app-console-account-queue
volumes:
- ./:/var/www/html/
env_file: .env
web:
build: ./docker/nginx
links:
- app
volumes_from:
- app
environment:
- AUTHSERVER_HOST=authserver.ely.by
- PHP_LINK=app
node-dev-server:
build: ./frontend
ports:
- "8080:8080"
volumes:
- ./frontend/:/usr/src/app/
environment:
DOCKERIZED: "true"
app-console-account-queue:
build: .
volumes:
- ./:/var/www/html/
command: ./docker/wait-for-it.sh rabbitmq:5672 -- ./yii account-queue
links:
- db
- redis
- rabbitmq
- app:php
env_file: .env
networks:
- default
- nginx-proxy
db:
build: ./docker/mariadb
environment:
MYSQL_ROOT_PASSWORD: ""
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
MYSQL_DATABASE: "ely_accounts"
MYSQL_USER: "ely_accounts_user"
MYSQL_PASSWORD: "ely_accounts_password"
env_file: .env
volumes:
- ./data/mysql:/var/lib/mysql
redis:
image: redis:3.0
image: redis:3.0-alpine
volumes:
- ./data/redis:/data
rabbitmq:
build: ./docker/rabbitmq
image: rabbitmq:3.6-management
env_file: .env
environment:
RABBITMQ_DEFAULT_USER: "ely-accounts-app"
RABBITMQ_DEFAULT_PASS: "ely-accounts-app-password"
RABBITMQ_DEFAULT_VHOST: "/ely.by"
ports:
- "15672:15672" # Manager interface
- VIRTUAL_HOST=rabbitmq.account.ely.by.local
- VIRTUAL_PORT=15672
networks:
- default
- nginx-proxy
phpmyadmin:
build: ./docker/phpmyadmin
@ -68,7 +50,14 @@ services:
- PMA_ARBITRARY=1
- PMA_USER=root
- PMA_PASSWORD=
ports:
- "8181:80"
links:
- VIRTUAL_HOST=pma.account.ely.by.local
depends_on:
- db
networks:
- default
- nginx-proxy
networks:
nginx-proxy:
external:
name: nginx-proxy

View File

@ -1,3 +1,6 @@
FROM mariadb:10.0
COPY mariadb.cnf /etc/mysql/conf.d
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["mysqld"]

View File

@ -1,4 +1,4 @@
FROM nginx:1.11
FROM nginx:1.11-alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY account.ely.by.conf.template /etc/nginx/conf.d/account.ely.by.conf.template
@ -7,4 +7,5 @@ COPY run.sh /run.sh
RUN rm /etc/nginx/conf.d/default.conf \
&& chmod a+x /run.sh
CMD ["/run.sh"]
ENTRYPOINT ["/run.sh"]
CMD ["nginx", "-g", "daemon off;"]

View File

@ -34,7 +34,7 @@ server {
}
location ~* \.php$ {
fastcgi_pass ${PHP_LINK}:9000;
fastcgi_pass php:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SERVER_NAME $host;

View File

@ -1,4 +1,5 @@
#!/usr/bin/env bash
#!/usr/bin/env sh
envsubst '$AUTHSERVER_HOST:$PHP_LINK' < /etc/nginx/conf.d/account.ely.by.conf.template > /etc/nginx/conf.d/default.conf
nginx -g 'daemon off;'
envsubst '$AUTHSERVER_HOST' < /etc/nginx/conf.d/account.ely.by.conf.template > /etc/nginx/conf.d/default.conf
exec "$@"

33
docker/php/entrypoint.sh Normal file
View File

@ -0,0 +1,33 @@
#!/bin/bash
cd /var/www/html
if [ "$1" = 'bash' ]
then
exec "$@"
exit 0
fi
# Переносим vendor, если его нету или он изменился (или затёрся силами volume)
if ! cmp -s ./../vendor/autoload.php ./vendor/autoload.php
then
echo "vendor have diffs..."
echo "removing exists vendor"
rm -rf ./vendor
echo "copying new one"
cp -r ./../vendor ./vendor
fi
# Переносим dist, если его нету или он изменился (или затёрся силами volume)
if ! cmp -s ./../dist/index.html ./frontend/dist/index.html
then
echo "frontend dist have diffs..."
echo "removing exists dist"
rm -rf ./frontend/dist
echo "copying new one"
cp -r ./../dist ./frontend/dist
fi
wait-for-it db:3306 -- "./yii migrate/up --interactive=0"
exec "$@"

View File

@ -0,0 +1,36 @@
[supervisord]
logfile=/tmp/supervisord.log ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10 ; (num of main logfile rotation backups;default 10)
loglevel=info ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false ; (start in foreground if true;default false)
minfds=1024 ; (min. avail startup file descriptors;default 1024)
minprocs=200 ; (min. avail process descriptors;default 200)
user=root
; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
[supervisorctl]
serverurl=unix:///dev/shm/supervisor.sock ; use a unix:// URL for a unix socket
[program:php-fpm]
command=php-fpm
autostart=true
autorestart=true
priority=5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[program:account-queue-worker]
directory=/var/www/html
command=wait-for-it rabbitmq:5672 -- php yii account-queue
autostart=true
autorestart=true
priority=10

View File

@ -3,3 +3,6 @@ FROM phpmyadmin/phpmyadmin
RUN printf "\n\nrequire('./config.local.php');\n" >> /www/config.inc.php
COPY config.local.php /www/
ENTRYPOINT [ "/run.sh" ]
CMD ["phpmyadmin"]

View File

@ -1,5 +0,0 @@
FROM rabbitmq:3.6
RUN rabbitmq-plugins enable rabbitmq_management \
&& rabbitmq-plugins enable rabbitmq_web_stomp \
&& rabbitmq-plugins enable rabbitmq_mqtt

View File

@ -1,26 +0,0 @@
<?php
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '',
'enableCsrfValidation' => false,
],
'reCaptcha' => [
'public' => '',
'secret' => '',
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;

View File

@ -1,5 +0,0 @@
<?php
return [
'userSecret' => 'some-long-secret-key',
'authserverDomain' => 'http://authserver.ely.by.local',
];

View File

@ -1,18 +0,0 @@
<?php
// NOTE: Make sure this file is not accessible when deployed to production
if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) {
die('You are not allowed to access this file.');
}
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');
$config = require(__DIR__ . '/../../tests/codeception/config/api/acceptance.php');
(new yii\web\Application($config))->run();

View File

@ -1,18 +0,0 @@
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);
$application->run();

View File

@ -1,29 +0,0 @@
<?php
return [
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=ely_accounts',
'username' => 'root',
'password' => '',
],
'mailer' => [
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'redis' => [
'hostname' => 'localhost',
'password' => null,
'port' => 6379,
'database' => 0,
],
'amqp' => [
'host' => 'localhost',
'port' => 5672,
'user' => 'ely-accounts-app',
'password' => 'app-password',
'vhost' => '/account.ely.by',
],
],
];

View File

@ -1,5 +0,0 @@
<?php
return [
'fromEmail' => 'account@ely.by',
'supportEmail' => 'support@ely.by',
];

View File

@ -1,3 +0,0 @@
<?php
return [
];

View File

@ -1,28 +0,0 @@
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/vendor/autoload.php');
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/common/config/bootstrap.php');
require(__DIR__ . '/console/config/bootstrap.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/common/config/main.php'),
require(__DIR__ . '/common/config/main-local.php'),
require(__DIR__ . '/console/config/main.php'),
require(__DIR__ . '/console/config/main-local.php')
);
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);

View File

@ -1,2 +0,0 @@
XDEBUG_CONFIG=remote_host=192.168.99.1
PHP_IDE_CONFIG=serverName=docker

View File

@ -1,25 +0,0 @@
<?php
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '',
],
'reCaptcha' => [
'public' => '',
'secret' => '',
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = \yii\debug\Module::class;
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = \yii\gii\Module::class;
}
return $config;

View File

@ -1,5 +0,0 @@
<?php
return [
'userSecret' => 'some-long-secret-key',
'authserverDomain' => 'https://authserver.ely.by',
];

View File

@ -1,18 +0,0 @@
<?php
// NOTE: Make sure this file is not accessible when deployed to production
if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) {
die('You are not allowed to access this file.');
}
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');
$config = require(__DIR__ . '/../../tests/codeception/config/api/acceptance.php');
(new yii\web\Application($config))->run();

View File

@ -1,18 +0,0 @@
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);
$application->run();

View File

@ -1,26 +0,0 @@
<?php
return [
'components' => [
'db' => [
'dsn' => 'mysql:host=db;dbname=ely_accounts',
'username' => 'ely_accounts_user',
'password' => 'ely_accounts_password',
],
'mailer' => [
'useFileTransport' => true,
],
'redis' => [
'hostname' => 'redis',
'password' => null,
'port' => 6379,
'database' => 0,
],
'amqp' => [
'host' => 'rabbitmq',
'port' => 5672,
'user' => 'ely-accounts-app',
'password' => 'ely-accounts-app-password',
'vhost' => '/ely.by',
],
],
];

View File

@ -1,5 +0,0 @@
<?php
return [
'fromEmail' => 'account@ely.by',
'supportEmail' => 'support@ely.by',
];

View File

@ -1,7 +0,0 @@
<?php
return [
'bootstrap' => ['gii'],
'modules' => [
'gii' => \yii\gii\Module::class,
],
];

View File

@ -1,3 +0,0 @@
<?php
return [
];

View File

@ -1,28 +0,0 @@
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/vendor/autoload.php');
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/common/config/bootstrap.php');
require(__DIR__ . '/console/config/bootstrap.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/common/config/main.php'),
require(__DIR__ . '/common/config/main-local.php'),
require(__DIR__ . '/console/config/main.php'),
require(__DIR__ . '/console/config/main-local.php')
);
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);

View File

@ -1,73 +0,0 @@
<?php
/**
* The manifest of files that are local to specific environment.
* This file returns a list of environments that the application
* may be installed under. The returned data must be in the following
* format:
*
* ```php
* return [
* 'environment name' => [
* 'path' => 'directory storing the local files',
* 'skipFiles' => [
* // list of files that should only copied once and skipped if they already exist
* ],
* 'setWritable' => [
* // list of directories that should be set writable
* ],
* 'setExecutable' => [
* // list of files that should be set executable
* ],
* 'setCookieValidationKey' => [
* // list of config files that need to be inserted with automatically generated cookie validation keys
* ],
* 'createSymlink' => [
* // list of symlinks to be created. Keys are symlinks, and values are the targets.
* ],
* ],
* ];
* ```
*/
return [
'Development' => [
'path' => 'dev',
'setWritable' => [
'api/runtime',
'api/web/assets',
],
'setExecutable' => [
'yii',
'tests/codeception/bin/yii',
],
'setCookieValidationKey' => [
'api/config/main-local.php',
],
],
'Docker' => [
'path' => 'docker',
'setWritable' => [
'api/runtime',
'api/web/assets',
],
'setExecutable' => [
'yii',
'tests/codeception/bin/yii',
],
'setCookieValidationKey' => [
'api/config/main-local.php',
],
],
'Production' => [
'path' => 'prod',
'setWritable' => [
'api/runtime',
'api/web/assets',
],
'setExecutable' => [
'yii',
],
'setCookieValidationKey' => [
'api/config/main-local.php',
],
],
];

View File

@ -1,13 +0,0 @@
<?php
return [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '',
],
'reCaptcha' => [
'public' => '',
'secret' => '',
],
],
];

View File

@ -1,5 +0,0 @@
<?php
return [
'userSecret' => 'some-long-secret-key',
'authserverDomain' => 'https://authserver.ely.by',
];

View File

@ -1,18 +0,0 @@
<?php
defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_ENV') or define('YII_ENV', 'prod');
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);
$application->run();

View File

@ -1,23 +0,0 @@
<?php
return [
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=ely_accounts',
'username' => 'root',
'password' => '',
],
'redis' => [
'hostname' => 'localhost',
'password' => null,
'port' => 6379,
'database' => 0,
],
'amqp' => [
'host' => 'localhost',
'port' => 5672,
'user' => 'ely-accounts-app',
'password' => 'app-password',
'vhost' => '/account.ely.by',
],
],
];

View File

@ -1,5 +0,0 @@
<?php
return [
'fromEmail' => 'account@ely.by',
'supportEmail' => 'support@ely.by',
];

View File

@ -1,3 +0,0 @@
<?php
return [
];

View File

@ -1,3 +0,0 @@
<?php
return [
];

View File

@ -1,28 +0,0 @@
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
defined('YII_DEBUG') or define('YII_DEBUG', false);
defined('YII_ENV') or define('YII_ENV', 'prod');
require(__DIR__ . '/vendor/autoload.php');
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/common/config/bootstrap.php');
require(__DIR__ . '/console/config/bootstrap.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/common/config/main.php'),
require(__DIR__ . '/common/config/main-local.php'),
require(__DIR__ . '/console/config/main.php'),
require(__DIR__ . '/console/config/main-local.php')
);
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);

209
init
View File

@ -1,209 +0,0 @@
#!/usr/bin/env php
<?php
/**
* Yii Application Initialization Tool
*
* In order to run in non-interactive mode:
*
* init --env=Development --overwrite=n
*
* @author Alexander Makarov <sam@rmcreative.ru>
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
if (!extension_loaded('openssl')) {
die('The OpenSSL PHP extension is required by Yii2.');
}
$params = getParams();
$root = str_replace('\\', '/', __DIR__);
$envs = require("$root/environments/index.php");
$envNames = array_keys($envs);
echo "Yii Application Initialization Tool v1.0\n\n";
$envName = null;
if (empty($params['env']) || $params['env'] === '1') {
echo "Which environment do you want the application to be initialized in?\n\n";
foreach ($envNames as $i => $name) {
echo " [$i] $name\n";
}
echo "\n Your choice [0-" . (count($envs) - 1) . ', or "q" to quit] ';
$answer = trim(fgets(STDIN));
if (!ctype_digit($answer) || !in_array($answer, range(0, count($envs) - 1))) {
echo "\n Quit initialization.\n";
exit(0);
}
if (isset($envNames[$answer])) {
$envName = $envNames[$answer];
}
} else {
$envName = $params['env'];
}
if (!in_array($envName, $envNames)) {
$envsList = implode(', ', $envNames);
echo "\n $envName is not a valid environment. Try one of the following: $envsList. \n";
exit(2);
}
$env = $envs[$envName];
if (empty($params['env'])) {
echo "\n Initialize the application under '{$envNames[$answer]}' environment? [yes|no] ";
$answer = trim(fgets(STDIN));
if (strncasecmp($answer, 'y', 1)) {
echo "\n Quit initialization.\n";
exit(0);
}
}
echo "\n Start initialization ...\n\n";
$files = getFileList("$root/environments/{$env['path']}");
if (isset($env['skipFiles'])) {
$skipFiles = $env['skipFiles'];
array_walk($skipFiles, function(&$value) use($env, $root) { $value = "$root/$value"; });
$files = array_diff($files, array_intersect_key($env['skipFiles'], array_filter($skipFiles, 'file_exists')));
}
$all = false;
foreach ($files as $file) {
if (!copyFile($root, "environments/{$env['path']}/$file", $file, $all, $params)) {
break;
}
}
$callbacks = ['setCookieValidationKey', 'setWritable', 'setExecutable', 'createSymlink'];
foreach ($callbacks as $callback) {
if (!empty($env[$callback])) {
$callback($root, $env[$callback]);
}
}
echo "\n ... initialization completed.\n\n";
function getFileList($root, $basePath = '')
{
$files = [];
$handle = opendir($root);
while (($path = readdir($handle)) !== false) {
if ($path === '.git' || $path === '.svn' || $path === '.' || $path === '..') {
continue;
}
$fullPath = "$root/$path";
$relativePath = $basePath === '' ? $path : "$basePath/$path";
if (is_dir($fullPath)) {
$files = array_merge($files, getFileList($fullPath, $relativePath));
} else {
$files[] = $relativePath;
}
}
closedir($handle);
return $files;
}
function copyFile($root, $source, $target, &$all, $params)
{
if (!is_file($root . '/' . $source)) {
echo " skip $target ($source not exist)\n";
return true;
}
if (is_file($root . '/' . $target)) {
if (file_get_contents($root . '/' . $source) === file_get_contents($root . '/' . $target)) {
echo " unchanged $target\n";
return true;
}
if ($all) {
echo " overwrite $target\n";
} else {
echo " exist $target\n";
echo " ...overwrite? [Yes|No|All|Quit] ";
$answer = !empty($params['overwrite']) ? $params['overwrite'] : trim(fgets(STDIN));
if (!strncasecmp($answer, 'q', 1)) {
return false;
} else {
if (!strncasecmp($answer, 'y', 1)) {
echo " overwrite $target\n";
} else {
if (!strncasecmp($answer, 'a', 1)) {
echo " overwrite $target\n";
$all = true;
} else {
echo " skip $target\n";
return true;
}
}
}
}
file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
return true;
}
echo " generate $target\n";
@mkdir(dirname($root . '/' . $target), 0777, true);
file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
return true;
}
function getParams()
{
$rawParams = [];
if (isset($_SERVER['argv'])) {
$rawParams = $_SERVER['argv'];
array_shift($rawParams);
}
$params = [];
foreach ($rawParams as $param) {
if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) {
$name = $matches[1];
$params[$name] = isset($matches[3]) ? $matches[3] : true;
} else {
$params[] = $param;
}
}
return $params;
}
function setWritable($root, $paths)
{
foreach ($paths as $writable) {
echo " chmod 0777 $writable\n";
@chmod("$root/$writable", 0777);
}
}
function setExecutable($root, $paths)
{
foreach ($paths as $executable) {
echo " chmod 0755 $executable\n";
@chmod("$root/$executable", 0755);
}
}
function setCookieValidationKey($root, $paths)
{
foreach ($paths as $file) {
echo " generate cookie validation key in $file\n";
$file = $root . '/' . $file;
$length = 32;
$bytes = openssl_random_pseudo_bytes($length);
$key = strtr(substr(base64_encode($bytes), 0, $length), '+/=', '_-.');
$content = preg_replace('/(("|\')cookieValidationKey("|\')\s*=>\s*)(""|\'\')/', "\\1'$key'", file_get_contents($file));
file_put_contents($file, $content);
}
}
function createSymlink($root, $links) {
foreach ($links as $link => $target) {
echo " symlink " . $root . "/" . $target . " " . $root . "/" . $link . "\n";
//first removing folders to avoid errors if the folder already exists
@rmdir($root . "/" . $link);
@symlink($root . "/" . $target, $root . "/" . $link);
}
}

View File

@ -1,20 +0,0 @@
@echo off
rem -------------------------------------------------------------
rem Yii command line init script for Windows.
rem
rem @author Qiang Xue <qiang.xue@gmail.com>
rem @link http://www.yiiframework.com/
rem @copyright Copyright (c) 2008 Yii Software LLC
rem @license http://www.yiiframework.com/license/
rem -------------------------------------------------------------
@setlocal
set YII_PATH=%~dp0
if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe
"%PHP_COMMAND%" "%YII_PATH%init" %*
@endlocal

View File

@ -1,24 +1,25 @@
<?php
use Codeception\Configuration;
use Codeception\Specify\Config;
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', dirname(dirname(dirname(__DIR__))));
defined('API_ENTRY_URL') or define('API_ENTRY_URL', parse_url(Configuration::config()['config']['test_entry_url'], PHP_URL_PATH));
defined('API_ENTRY_FILE') or define('API_ENTRY_FILE', __DIR__ . '/../../../api/web/index.php');
defined('API_ENTRY_URL') or define('API_ENTRY_URL', parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_PATH));
defined('API_ENTRY_FILE') or define('API_ENTRY_FILE', YII_APP_BASE_PATH . '/api/web/index-test.php');
require_once(YII_APP_BASE_PATH . '/vendor/autoload.php');
require_once(YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php');
require_once(YII_APP_BASE_PATH . '/common/config/bootstrap.php');
require_once(YII_APP_BASE_PATH . '/api/config/bootstrap.php');
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../../vendor/yiisoft/yii2/Yii.php';
require_once __DIR__ . '/../../../common/config/bootstrap.php';
require_once __DIR__ . '/../../../api/config/bootstrap.php';
// set correct script paths
// the entry script file path for functional tests
$_SERVER['SCRIPT_FILENAME'] = API_ENTRY_FILE;
$_SERVER['SCRIPT_NAME'] = API_ENTRY_URL;
$_SERVER['SERVER_NAME'] = parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_HOST);
$_SERVER['SERVER_PORT'] = parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_PORT) ?: '80';
$_SERVER['SERVER_NAME'] = parse_url(Configuration::config()['config']['test_entry_url'], PHP_URL_HOST);
$_SERVER['SERVER_PORT'] = parse_url(Configuration::config()['config']['test_entry_url'], PHP_URL_PORT) ?: '80';
Yii::setAlias('@tests', dirname(dirname(__DIR__)));
\Codeception\Specify\Config::setDeepClone(false);
Config::setDeepClone(false);

View File

@ -12,9 +12,7 @@ settings:
memory_limit: 1024M
log: true
config:
# the entry script URL (with host info) for functional tests
# PLEASE ADJUST IT TO THE ACTUAL ENTRY SCRIPT URL
test_entry_url: http://localhost:8080/api/web/index-test.php
test_entry_url: http://localhost/api/web/index.php
coverage:
enabled: true
remote: true
@ -26,4 +24,4 @@ coverage:
- ../../../api/mails/*
- ../../../api/web/*
- ../../../api/runtime/*
c3url: 'http://localhost:8080/api/web/index-test.php'
c3url: 'http://localhost/api/web/index.php'

View File

@ -1,5 +1,4 @@
<?php
new yii\web\Application(require(dirname(dirname(__DIR__)) . '/config/api/functional.php'));
new yii\web\Application(require __DIR__ . '/../../config/api/functional.php');
\Codeception\Util\Autoload::registerSuffix('Steps', __DIR__ . DIRECTORY_SEPARATOR);

View File

@ -3,6 +3,10 @@ namespace codeception\api\unit\models;
use api\models\AccountIdentity;
use Codeception\Specify;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Token;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\common\_support\ProtectedCaller;
use tests\codeception\common\fixtures\AccountFixture;
@ -33,9 +37,13 @@ class AccountIdentityTest extends DbTestCase {
* @expectedExceptionMessage Token expired
*/
public function testFindIdentityByAccessTokenWithExpiredToken() {
$expiredToken = 'eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODA4MCIsImlzcyI6Imh0d' .
'HA6XC9cL2xvY2FsaG9zdDo4MDgwIiwiaWF0IjoxNDY0NTkzMTkzLCJleHAiOjE0NjQ1OTY3OTN9.DV' .
'8uwh0OQhBYXkrNvxwJeO-kEjb9MQeLr3-6GoHM7RY';
$token = new Token();
$token->addClaim(new Claim\Audience('http://localhost'));
$token->addClaim(new Claim\Issuer('http://localhost'));
$token->addClaim(new Claim\IssuedAt(1464593193));
$token->addClaim(new Claim\Expiration(1464596793));
$token->addClaim(new Claim\JwtId($this->accounts['admin']['id']));
$expiredToken = (new Jwt())->serialize($token, EncryptionFactory::create(Yii::$app->user->getAlgorithm()));
AccountIdentity::findIdentityByAccessToken($expiredToken);
}

View File

@ -1,6 +1,7 @@
<?php
namespace tests\codeception\api\models\authentication;
use api\components\ReCaptcha\Validator;
use api\models\authentication\RegistrationForm;
use Codeception\Specify;
use common\models\Account;
@ -25,6 +26,11 @@ class RegistrationFormTest extends DbTestCase {
return 'testing_message.eml';
};
$this->mockRequest();
Yii::$container->set(Validator::class, new class extends Validator {
public function validateValue($value) {
return null;
}
});
}
protected function tearDown() {

View File

@ -1,6 +1,7 @@
<?php
namespace tests\codeception\api\models\authentication;
use api\components\ReCaptcha\Validator;
use api\models\authentication\RepeatAccountActivationForm;
use Codeception\Specify;
use common\models\EmailActivation;
@ -23,6 +24,11 @@ class RepeatAccountActivationFormTest extends DbTestCase {
$mailer->fileTransportCallback = function () {
return 'testing_message.eml';
};
Yii::$container->set(Validator::class, new class extends Validator {
public function validateValue($value) {
return null;
}
});
}
protected function tearDown() {

View File

@ -24,6 +24,9 @@ class RateLimiterTest extends TestCase {
/** @var RateLimiter|\PHPUnit_Framework_MockObject_MockObject $filter */
$filter = $this->getMockBuilder(RateLimiter::class)
->setConstructorArgs([[
'authserverDomain' => Yii::$app->params['authserverHost']
]])
->setMethods(['getServer'])
->getMock();
@ -54,7 +57,9 @@ class RateLimiterTest extends TestCase {
->method('getHostInfo')
->will($this->returnValue('http://authserver.ely.by'));
$filter = new RateLimiter();
$filter = new RateLimiter([
'authserverDomain' => Yii::$app->params['authserverHost']
]);
$filter->checkRateLimit(null, $request, null, null);
}
@ -86,6 +91,7 @@ class RateLimiterTest extends TestCase {
$filter = $this->getMockBuilder(RateLimiter::class)
->setConstructorArgs([[
'limit' => 3,
'authserverDomain' => Yii::$app->params['authserverHost'],
]])
->setMethods(['getServer'])
->getMock();

View File

@ -1,19 +1,9 @@
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once(YII_APP_BASE_PATH . '/vendor/autoload.php');
require_once(YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php');
require_once(YII_APP_BASE_PATH . '/common/config/bootstrap.php');
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../../vendor/yiisoft/yii2/Yii.php';
require_once __DIR__ . '/../../../common/config/bootstrap.php';
Yii::setAlias('@tests', dirname(dirname(__DIR__)));

View File

@ -1,21 +1,10 @@
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
require_once __DIR__ . '/_bootstrap.php';
$config = yii\helpers\ArrayHelper::merge(
require(YII_APP_BASE_PATH . '/common/config/main.php'),
require(YII_APP_BASE_PATH . '/common/config/main-local.php'),
require(YII_APP_BASE_PATH . '/console/config/main.php'),
require(YII_APP_BASE_PATH . '/console/config/main-local.php'),
require(dirname(__DIR__) . '/config/config.php')
\common\config\ConfigLoader::load('console'),
require(__DIR__ . '/../config/config.php')
);
$application = new yii\console\Application($config);

View File

@ -1,20 +0,0 @@
@echo off
rem -------------------------------------------------------------
rem Yii command line bootstrap script for Windows.
rem
rem @author Qiang Xue <qiang.xue@gmail.com>
rem @link http://www.yiiframework.com/
rem @copyright Copyright (c) 2008 Yii Software LLC
rem @license http://www.yiiframework.com/license/
rem -------------------------------------------------------------
@setlocal
set YII_PATH=%~dp0
if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe
"%PHP_COMMAND%" "%YII_PATH%yii" %*
@endlocal

View File

@ -2,11 +2,9 @@
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once(YII_APP_BASE_PATH . '/vendor/autoload.php');
require_once(YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php');
require_once(YII_APP_BASE_PATH . '/common/config/bootstrap.php');
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../../vendor/yiisoft/yii2/Yii.php';
require_once __DIR__ . '/../../../common/config/bootstrap.php';
// set correct script paths
$_SERVER['SERVER_NAME'] = 'localhost';

View File

@ -2,7 +2,7 @@
namespace tests\codeception\common\_support;
use Codeception\Module;
use Codeception\TestCase;
use Codeception\TestInterface;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\AccountSessionFixture;
use tests\codeception\common\fixtures\EmailActivationFixture;
@ -32,17 +32,17 @@ class FixtureHelper extends Module {
getFixture as protected;
}
public function _before(TestCase $test) {
public function _before(TestInterface $test) {
$this->loadFixtures();
}
public function _after(TestCase $test) {
public function _after(TestInterface $test) {
$this->unloadFixtures();
}
public function globalFixtures() {
return [
InitDbFixture::className(),
InitDbFixture::class,
];
}

View File

@ -3,7 +3,7 @@ namespace codeception\common\unit\behaviors;
use Codeception\Specify;
use common\behaviors\PrimaryKeyValueBehavior;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\unit\TestCase;
use yii\db\ActiveRecord;
class PrimaryKeyValueBehaviorTest extends TestCase {

View File

@ -6,7 +6,7 @@ use common\models\confirmations\ForgotPassword;
use common\models\confirmations\RegistrationConfirmation;
use common\models\EmailActivation;
use tests\codeception\common\fixtures\EmailActivationFixture;
use tests\codeception\console\unit\DbTestCase;
use tests\codeception\common\unit\DbTestCase;
class EmailActivationTest extends DbTestCase {
use Specify;

View File

@ -9,7 +9,12 @@ return [
'secret' => 'private-key',
],
],
'modules' => [
'authserver' => [
'baseDomain' => 'http://localhost',
],
],
'params' => [
'authserverDomain' => 'http://authserver.ely.by',
'authserverHost' => 'authserver.ely.by',
],
];

View File

@ -2,16 +2,9 @@
$_SERVER['SCRIPT_FILENAME'] = API_ENTRY_FILE;
$_SERVER['SCRIPT_NAME'] = API_ENTRY_URL;
/**
* Application configuration for api functional tests
*/
return yii\helpers\ArrayHelper::merge(
require(YII_APP_BASE_PATH . '/common/config/main.php'),
require(YII_APP_BASE_PATH . '/common/config/main-local.php'), require(YII_APP_BASE_PATH . '/api/config/main.php'),
require(YII_APP_BASE_PATH . '/api/config/main-local.php'),
require(dirname(__DIR__) . '/config.php'),
require(dirname(__DIR__) . '/functional.php'),
require(__DIR__ . '/config.php'),
[
]
\common\config\ConfigLoader::load('api'),
require __DIR__ . '/../config.php',
require __DIR__ . '/../functional.php',
require __DIR__ . '/config.php'
);

View File

@ -1,15 +1,7 @@
<?php
/**
* Application configuration for api unit tests
*/
return yii\helpers\ArrayHelper::merge(
require(YII_APP_BASE_PATH . '/common/config/main.php'),
require(YII_APP_BASE_PATH . '/common/config/main-local.php'), require(YII_APP_BASE_PATH . '/api/config/main.php'),
require(YII_APP_BASE_PATH . '/api/config/main-local.php'),
require(dirname(__DIR__) . '/config.php'),
require(dirname(__DIR__) . '/unit.php'),
require(__DIR__ . '/config.php'),
[
]
\common\config\ConfigLoader::load('api'),
require __DIR__ . '/../config.php',
require __DIR__ . '/../unit.php',
require __DIR__ . '/config.php'
);

View File

@ -1,12 +1,8 @@
<?php
/**
* Application config for common unit tests
*/
return yii\helpers\ArrayHelper::merge(
require(YII_APP_BASE_PATH . '/common/config/main.php'),
require(YII_APP_BASE_PATH . '/common/config/main-local.php'),
require(dirname(__DIR__) . '/config.php'),
require(dirname(__DIR__) . '/unit.php'),
\common\config\ConfigLoader::load('common'),
require __DIR__ . '/../config.php',
require __DIR__ . '/../unit.php',
[
'id' => 'app-common',
'basePath' => dirname(__DIR__),

View File

@ -3,7 +3,7 @@ return [
'language' => 'en-US',
'controllerMap' => [
'fixture' => [
'class' => 'yii\faker\FixtureController',
'class' => yii\faker\FixtureController::class,
'fixtureDataPath' => '@tests/codeception/common/fixtures/data',
'templatePath' => '@tests/codeception/common/templates/fixtures',
'namespace' => 'tests\codeception\common\fixtures',

View File

@ -1,14 +1,6 @@
<?php
/**
* Application configuration for console unit tests
*/
return yii\helpers\ArrayHelper::merge(
require(YII_APP_BASE_PATH . '/common/config/main.php'),
require(YII_APP_BASE_PATH . '/common/config/main-local.php'),
require(YII_APP_BASE_PATH . '/console/config/main.php'),
require(YII_APP_BASE_PATH . '/console/config/main-local.php'),
require(dirname(__DIR__) . '/config.php'),
require(dirname(__DIR__) . '/unit.php'),
[
]
\common\config\ConfigLoader::load('console'),
require __DIR__ . '/../config.php',
require __DIR__ . '/../unit.php'
);

View File

@ -1,18 +1,12 @@
<?php
/**
* Application configuration shared by all applications functional tests
*/
return [
'components' => [
'request' => [
// it's not recommended to run functional tests with CSRF validation enabled
// TODO: у нас вроде и без того нет проверки csrf
'enableCsrfValidation' => false,
'enableCookieValidation' => false,
// but if you absolutely need it set cookie domain to localhost
/*
'csrfCookie' => [
'domain' => 'localhost',
],
*/
],
],
];
];

View File

@ -1,7 +1,4 @@
<?php
/**
* Application configuration shared by all applications unit tests
*/
return [
];
];

View File

@ -2,12 +2,10 @@
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once(YII_APP_BASE_PATH . '/vendor/autoload.php');
require_once(YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php');
require_once(YII_APP_BASE_PATH . '/common/config/bootstrap.php');
require_once(YII_APP_BASE_PATH . '/console/config/bootstrap.php');
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../../vendor/yiisoft/yii2/Yii.php';
require_once __DIR__ . '/../../../common/config/bootstrap.php';
require_once __DIR__ . '/../../../console/config/bootstrap.php';
// set correct script paths
$_SERVER['SERVER_NAME'] = 'localhost';

View File

@ -1,17 +1,17 @@
version: '2'
services:
testphp:
build: ./..
links:
- testdb
- testredis
- testrabbit
extends:
file: ../docker-compose.dev.yml
service: app
volumes:
- ./../:/var/www/html/
env_file: ./../.env
testdb:
build: ./../docker/mariadb
extends:
file: ../docker-compose.dev.yml
service: db
environment:
MYSQL_ROOT_PASSWORD: ""
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
@ -20,10 +20,14 @@ services:
MYSQL_PASSWORD: "ely_accounts_tester_password"
testredis:
image: redis:3.0
extends:
file: ../docker-compose.dev.yml
service: redis
testrabbit:
build: ./../docker/rabbitmq
extends:
file: ../docker-compose.dev.yml
service: rabbitmq
environment:
RABBITMQ_DEFAULT_USER: "ely-accounts-tester"
RABBITMQ_DEFAULT_PASS: "tester-password"

16
yii Executable file
View File

@ -0,0 +1,16 @@
#!/usr/bin/env php
<?php
require(__DIR__ . '/vendor/autoload.php');
defined('YII_DEBUG') or define('YII_DEBUG', (boolean)getenv('YII_DEBUG'));
defined('YII_ENV') or define('YII_ENV', getenv('YII_ENV'));
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/common/config/bootstrap.php');
require(__DIR__ . '/console/config/bootstrap.php');
$config = \common\config\ConfigLoader::load('console');
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);

20
yii.bat
View File

@ -1,20 +0,0 @@
@echo off
rem -------------------------------------------------------------
rem Yii command line bootstrap script for Windows.
rem
rem @author Qiang Xue <qiang.xue@gmail.com>
rem @link http://www.yiiframework.com/
rem @copyright Copyright (c) 2008 Yii Software LLC
rem @license http://www.yiiframework.com/license/
rem -------------------------------------------------------------
@setlocal
set YII_PATH=%~dp0
if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe
"%PHP_COMMAND%" "%YII_PATH%yii" %*
@endlocal