Retire this repository as it has moved

This project is no longer developed on opendev and has moved to github.
Perform project retirement to clean up the opendev content. In
particular we want to remove zuul configs that have errors, but also
give people hints to the current code repository.

Depends-On: https://review.opendev.org/c/openstack/project-config/+/818170
Change-Id: Icd4d25d60d96d57eb99f1bcb4055a7bb4ae10b30
This commit is contained in:
Clark Boylan 2021-11-16 14:35:44 -08:00
parent 2a16bfa1fb
commit f878d60979
1001 changed files with 10 additions and 116661 deletions

View File

@ -1,17 +0,0 @@
{
"presets": [
[
"env",
{
"targets": {
"node": "current"
}
}
],
"flow",
"react"
],
"plugins": [
"transform-object-rest-spread"
]
}

View File

@ -1,82 +0,0 @@
APP_ENV=local
APP_DEBUG=true
DEV_EMAIL_TO=smarcet@gmail.com
APP_KEY=SomeRandomString
APP_URL=http://localhost
APP_OAUTH_2_0_CLIENT_ID=clientid
APP_OAUTH_2_0_CLIENT_SECRET=clientsecret
APP_OAUTH_2_0_AUTH_SERVER_BASE_URL=http://localhost
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
DB_USE_SSL=false
DB_MYSQL_ATTR_SSL_CA=
DB_MYSQL_ATTR_SSL_KEY=
DB_MYSQL_ATTR_SSL_CERT=
DB_MYSQL_ATTR_SSL_CIPHER=DHE-RSA-AES256-SHA
REDIS_HOST=127.0.0.1
REDIS_PORT=port
REDIS_DB=0
REDIS_PASSWORD=
CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_COOKIE_DOMAIN=
SESSION_COOKIE_SECURE=false
QUEUE_DRIVER=database
QUEUE_CONN=
QUEUE_DATABASE=
MAIL_DRIVER=sendgrid
SENDGRID_API_KEY='YOUR_SENDGRID_API_KEY'
CORS_ALLOWED_HEADERS=origin, content-type, accept, authorization, x-requested-with
CORS_ALLOWED_METHODS=GET, POST, OPTIONS, PUT, DELETE
CORS_USE_PRE_FLIGHT_CACHING=true
CORS_MAX_AGE=3200
CORS_EXPOSED_HEADERS=
CURL_TIMEOUT=3600
CURL_ALLOWS_REDIRECT=false
CURL_VERIFY_SSL_CERT=false
ASSETS_BASE_URL=http://www.openstack.org
SSL_ENABLED=true
DB_LOG_ENABLED=true
ACCESS_TOKEN_CACHE_LIFETIME=300
API_RESPONSE_CACHE_LIFETIME=600
LOG_EMAIL_TO=smarcet@gmail.com
LOG_EMAIL_FROM=smarcet@gmail.com
LOG_LEVEL=info
EVENTBRITE_OAUTH2_PERSONAL_TOKEN=
RECAPTCHA_PUBLIC_KEY=
RECAPTCHA_PRIVATE_KEY=
BANNING_ENABLE=
SUPPORT_EMAIL=
USER_SPAM_PROCESSOR_TO=
MAIL_FROM_EMAIL="noreply@openstack.org"
MAIL_FROM_NAME="noreply@openstack.org"
## RABBIT MQ
RABBITMQ_EXCHANGE_NAME=databus-exchange
RABBITMQ_HOST=
RABBITMQ_PORT=5671
RABBITMQ_VHOST=databus
RABBITMQ_LOGIN=admin
RABBITMQ_PASSWORD=1qaz2wsx
RABBITMQ_QUEUE=default
RABBITMQ_SSL=true
RABBITMQ_SSL_CAFILE=/certs/rabbit/ca-osf.pem
RABBITMQ_SSL_LOCALCERT=/certs/rabbit/client-cert-osf.pem
RABBITMQ_SSL_LOCALKEY=/certs/rabbit/client-key-osf.pem
RABBITMQ_SSL_VERIFY_PEER=false

3
.gitattributes vendored
View File

@ -1,3 +0,0 @@
* text=auto
*.css linguist-vendored
*.less linguist-vendored

44
.gitignore vendored
View File

@ -1,44 +0,0 @@
/vendor
composer.phar
.idea/*
.tox
AUTHORS
ChangeLog
doc/build
*.egg
*.egg-info
*.log
/node_modules
.idea/
/public/storage
Homestead.yaml
Homestead.json
.env
.env.testing
storage/proxies
/public/assets/jquery-cookie/
/public/assets/crypto-js/
/public/assets/bootstrap-tagsinput/
/public/assets/fonts/
/public/assets/typeahead/
/public/assets/__common__.js
/public/assets/index.js
public/assets/index.js.map
public/assets/__common__.js.map
public/assets/images/
public/assets/svg/
public/assets/css/index.css.map
public/assets/css/index.css
public/assets/simplemde/
/public/assets/pwstrength-bootstrap/
/public/assets/sweetalert2/
/public/assets/urijs
/public/assets/uri.js
/public/assets/clipboard-copy-element/
_intellij_phpdebug_validator.php
/public/assets/chosen-js
/public/assets/moment
routes.txt
model.sql
.phpunit.result.cache
!/public/web.config

View File

@ -1,4 +1,4 @@
[gerrit] [gerrit]
host=review.opendev.org host=review.opendev.org
port=29418 port=29418
project=osf/openstackid.git project=openinfra/openstackid.git

View File

@ -1,46 +0,0 @@
- job:
name: openstackid-release-branch
parent: publish-openstack-artifacts
run: playbooks/openstackid-release-branch/run.yaml
post-run: playbooks/openstackid-release-branch/post.yaml
timeout: 1800
# OpenStackID needs MYSQL 5.7.x and will fail with newer MYSQL, Bionic has Java 5.7.x.
nodeset: ubuntu-bionic
- job:
# This is included into the osf/openstackid release pipeline from the
# openstack/project-config .zuul.d/projects.yaml
name: openstackid-release-master
parent: publish-openstack-artifacts
run: playbooks/openstackid-release-master/run.yaml
post-run: playbooks/openstackid-release-master/post.yaml
timeout: 1800
# OpenStackID needs MYSQL 5.7.x and will fail with newer MYSQL, Bionic has Java 5.7.x.
nodeset: ubuntu-bionic
- job:
name: openstackid-unittests
run: playbooks/openstackid-unittests/run.yaml
timeout: 1800
# OpenStackID needs MYSQL 5.7.x and will fail with newer MYSQL, Bionic has Java 5.7.x.
nodeset: ubuntu-bionic
- project:
name: osf/openstackid
check:
jobs:
- openstackid-unittests
- opendev-tox-docs:
nodeset: ubuntu-bionic
gate:
jobs:
- openstackid-unittests
- opendev-tox-docs:
nodeset: ubuntu-bionic
post:
jobs:
- openstackid-release-branch
promote:
jobs:
- promote-tox-docs-infra

View File

@ -1,3 +0,0 @@
# Contribution Guidelines
Please submit all issues and pull requests to the [laravel/framework](http://github.com/laravel/framework) repository!

View File

@ -1,66 +0,0 @@
<?php namespace App\Console\Commands;
/**
* Copyright 2017 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
/**
* Class CleanOAuth2StaleData
* @package Console\Commands
*/
final class CleanOAuth2StaleData extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'idp:oauth2-clean';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'idp:oauth2-clean';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clean OAuth2 stale data';
const IntervalInSeconds = 86400; // 1 day;
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// delete void access tokens
if (Schema::hasTable('oauth2_access_token')) {
$res = DB::table('oauth2_access_token')
->whereRaw("DATE_ADD(created_at, INTERVAL lifetime second) <= UTC_TIMESTAMP()")
->delete();
Log::debug(sprintf("CleanOAuth2StaleData::handle %s rows where deleted from oauth2_access_token", $res));
}
}
}

View File

@ -1,85 +0,0 @@
<?php namespace App\Console\Commands;
/**
* Copyright 2017 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
/**
* Class CleanOpenIdStaleData
* @package Console\Commands
*/
final class CleanOpenIdStaleData extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'idp:openid-clean';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'idp:openid-clean';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clean OpenId stale data';
const IntervalInSeconds = 86400; // 1 day;
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$interval = self::IntervalInSeconds;
if (Schema::hasTable('openid_associations')) {
// delete void associations
$res = DB::table('openid_associations')
->whereRaw("DATE_ADD(issued, INTERVAL lifetime second) <= UTC_TIMESTAMP()")
->delete();
Log::debug(sprintf("CleanOpenIdStaleData::handle %s rows where deleted from openid_associations", $res));
}
if (Schema::hasTable('user_exceptions_trail')) {
// delete old exceptions trails
$res = DB::table('user_exceptions_trail')
->whereRaw("DATE_ADD(created_at, INTERVAL {$interval} second) <= UTC_TIMESTAMP()")
->delete();
Log::debug(sprintf("CleanOpenIdStaleData::handle %s rows where deleted from user_exceptions_trail", $res));
}
if (Schema::hasTable('user_actions')) {
// delete old user actions
$res = DB::table('user_actions')
->whereRaw("DATE_ADD(created_at, INTERVAL 1 year) <= UTC_TIMESTAMP()")
->delete();
Log::debug(sprintf("CleanOpenIdStaleData::handle %s rows where deleted from user_actions", $res));
}
}
}

View File

@ -1,85 +0,0 @@
<?php namespace App\Console\Commands;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Auth\Group;
use Auth\User;
use Illuminate\Console\Command;
use LaravelDoctrine\ORM\Facades\EntityManager;
/**
* Class CreateSuperAdmin
* @package App\Console\Commands
*/
class CreateSuperAdmin extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'idp:create-super-admin {email} {password}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create Super Admin User';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
$email = trim($this->argument('email'));
$password = trim($this->argument('password'));
$user = EntityManager::getRepository(User::class)->findOneBy(['email' => $email]);
if(is_null($user)) {
$user = new User();
$user->setEmail($email);
$user->verifyEmail();
$user->setPassword($password);
EntityManager::persist($user);
EntityManager::flush();
}
$group = EntityManager::getRepository(Group::class)->findOneBy(['name' => 'super admins']);
if(is_null($group)){
$group = new Group();
$group->setName('super admins');
$group->setSlug('super-admins');
$group->setDefault(false);
$group->setActive(true);
EntityManager::persist($group);
EntityManager::flush();
}
$user->addToGroup($group);
EntityManager::persist($user);
EntityManager::flush();
}
}

View File

@ -1,4 +0,0 @@
env/
.idea/
__pycache__/
user_classifier.pickle

View File

@ -1,19 +0,0 @@
## Dependencies
````bas
$ sudo apt update
$ sudo apt install python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools python3-venv
libmysqlclient-dev
````
## Virtual Env
````bash
$ python3.6 -m venv env
$ source env/bin/activate
$ pip install -r requirements.txt
````

View File

@ -1,94 +0,0 @@
<?php namespace App\Console\Commands\SpammerProcess;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;
use Exception;
/**
* Class RebuildUserSpammerEstimator
* @package App\Console\Commands\SpammerProcess
*/
final class RebuildUserSpammerEstimator extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'user-spam:rebuild';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'user-spam:rebuild';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rebuild User spam estimator';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
try {
$connections = Config::get('database.connections', []);
$db = $connections['openstackid'] ?? [];
$host = $db['host'] ?? '';
$database = $db['database'] ?? '';
$username = $db['username'] ?? '';
$password = $db['password'] ?? '';
$command = sprintf(
'%s/app/Console/Commands/SpammerProcess/estimator_build.sh "%s" "%s" "%s" "%s" "%s"',
base_path(),
base_path() . '/app/Console/Commands/SpammerProcess',
$host,
$username,
$password,
$database
);
Log::debug(sprintf("RebuildUserSpammerEstimator::handle running command %s", $command));
$process = new Process($command);
$process->setTimeout(PHP_INT_MAX);
$process->setIdleTimeout(PHP_INT_MAX);
$process->run();
while ($process->isRunning()) {
}
$output = $process->getOutput();
Log::debug(sprintf("RebuildUserSpammerEstimator::handle output %s", $output));
if (!$process->isSuccessful()) {
throw new Exception("Process Error!");
}
}
catch (Exception $ex){
Log::error($ex);
}
}
}

View File

@ -1,138 +0,0 @@
<?php namespace App\Console\Commands\SpammerProcess;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\libs\Utils\CSVReader;
use App\Mail\UserSpammerProcessorResultsEmail;
use Auth\Repositories\IUserRepository;
use Auth\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Symfony\Component\Process\Process;
use Exception;
/**
* Class UserSpammerProcessor
* @package App\Console\Commands\SpammerProcess
*/
final class UserSpammerProcessor extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'user-spam:process';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'user-spam:process';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Process User spam estimator';
/**
* @var IUserRepository
*/
private $user_repository;
/**
* MemberSpammerProcessor constructor.
* @param IUserRepository $user_repository
*/
public function __construct(IUserRepository $user_repository)
{
parent::__construct();
$this->user_repository = $user_repository;
}
/**
* @throws Exception
*/
public function handle()
{
try {
$connections = Config::get('database.connections', []);
$db = $connections['openstackid'] ?? [];
$host = $db['host'] ?? '';
$database = $db['database'] ?? '';
$username = $db['username'] ?? '';
$password = $db['password'] ?? '';
$command = sprintf(
'%s/app/Console/Commands/SpammerProcess/estimator_process.sh "%s" "%s" "%s" "%s" "%s"',
base_path(),
base_path() . '/app/Console/Commands/SpammerProcess',
$host,
$username,
$password,
$database
);
Log::debug(sprintf("UserSpammerProcessor::handle running command %s", $command));
$process = new Process($command);
$process->setTimeout(PHP_INT_MAX);
$process->setIdleTimeout(PHP_INT_MAX);
$process->run();
while ($process->isRunning()) {
}
$csv_content = $process->getOutput();
Log::debug(sprintf("UserSpammerProcessor::handle output %s", $csv_content));
if (!$process->isSuccessful()) {
throw new Exception("Process Error!");
}
$rows = CSVReader::load($csv_content);
// send email with excerpt
$users = [];
foreach ($rows as $row) {
$user_id = intval($row["ID"]);
$type = $row["Type"];
$user = $this->user_repository->getById($user_id);
if (is_null($user) || !$user instanceof User) continue;
$users[] = [
'id' => $user->getId(),
'email' => $user->getEmail(),
'full_name' => $user->getFullName(),
'spam_type' => $type,
'edit_link' => URL::route("edit_user", ["user_id" => $user->getId()], true)
];
}
if (count($users) > 0 && !empty(Config::get('mail.user_spam_processor_to'))) {
Log::debug("UserSpammerProcessor::handle sending email");
Mail::queue(new UserSpammerProcessorResultsEmail($users));
}
}
catch (Exception $ex){
Log::error($ex);
}
}
}

View File

@ -1,36 +0,0 @@
# -*- coding: utf-8 -*-
# !/usr/bin/env python
#
# Copyright (c) 2020 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from openstack_member_spammer_estimator import EstimatorBuilder
import os
# params
db_host = sys.argv[1]
db_user = sys.argv[2]
db_user_password = sys.argv[3]
db_name = sys.argv[4]
filename = 'user_classifier.pickle'
builder = EstimatorBuilder(filename=filename, db_host=db_host, db_user=db_user, db_user_password=db_user_password,
db_name=db_name)
script_dir = os.path.dirname(__file__)
pickle_file = os.path.join(script_dir, )
if os.path.exists(pickle_file):
os.remove(pickle_file)
builder.build()

View File

@ -1,31 +0,0 @@
#!/bin/bash
# Copyright (c) 2020 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
WORK_DIR=$1
DB_HOST=$2
DB_USER=$3
DB_PASSWORD=$4
DB_NAME=$5
export PYTHONPATH="$PYTHONPATH:$WORK_DIR";
cd $WORK_DIR;
source env/bin/activate;
python estimator_build.py $DB_HOST $DB_USER $DB_PASSWORD $DB_NAME;
deactivate;

View File

@ -1,41 +0,0 @@
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright (c) 2020 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from openstack_member_spammer_estimator import EstimatorClassifier
import os
# params
db_host = sys.argv[1]
db_user = sys.argv[2]
db_user_password = sys.argv[3]
db_name = sys.argv[4]
filename = 'user_classifier.pickle'
classifier = EstimatorClassifier(db_host=db_host, db_user=db_user, db_user_password=db_user_password, db_name=db_name)
script_dir = os.path.dirname(__file__)
pickle_file = os.path.join(script_dir, filename)
if not os.path.exists(pickle_file):
raise Exception('File %s does not exists!' % pickle_file)
res = classifier.classify(pickle_file)
# output CSV file
print("ID,Type")
for row in res:
print("%s,%s" % row)

View File

@ -1,31 +0,0 @@
#!/bin/bash
# Copyright (c) 2017 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
WORK_DIR=$1
DB_HOST=$2
DB_USER=$3
DB_PASSWORD=$4
DB_NAME=$5
export PYTHONPATH="$PYTHONPATH:$WORK_DIR";
cd $WORK_DIR;
source env/bin/activate;
python estimator_process.py $DB_HOST $DB_USER $DB_PASSWORD $DB_NAME;
deactivate;

View File

@ -1,27 +0,0 @@
openstack-member-spammer-estimator==1.0.2
pkg-resources==0.0.0
attrs==19.3.0
configparser==4.0.2
HTMLParser==0.0.2
importlib-metadata==1.5.0
joblib==0.14.1
more-itertools==8.2.0
mysqlclient==1.4.6
nltk==3.4.5
numpy==1.18.1
packaging==20.3
pandas==0.24.2
pluggy==0.13.1
py==1.8.1
pyparsing==2.4.6
pytest==5.3.5
python-dateutil==2.8.1
pytz==2019.3
scikit-learn==0.22.2.post1
scipy==1.4.1
six==1.14.0
sklearn==0.0
wcwidth==0.1.8
zipp==1.2.0
singledispatch==3.4.0.3
six==1.14.0

View File

@ -1,50 +0,0 @@
<?php namespace App\Console;
/**
* Copyright 2017 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
/**
* Class Kernel
* @package App\Console
*/
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
// Commands\Inspire::class,
Commands\CleanOAuth2StaleData::class,
Commands\CleanOpenIdStaleData::class,
Commands\CreateSuperAdmin::class,
Commands\SpammerProcess\RebuildUserSpammerEstimator::class,
Commands\SpammerProcess\UserSpammerProcessor::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('idp:oauth2-clean')->dailyAt("02:30")->withoutOverlapping();
$schedule->command('idp:openid-clean')->dailyAt("03:30")->withoutOverlapping();
// user spammer
$schedule->command('user-spam:rebuild')->dailyAt("02:30")->withoutOverlapping();
$schedule->command('user-spam:process')->dailyAt("03:30")->withoutOverlapping();
}
}

View File

@ -1,8 +0,0 @@
<?php
namespace App\Events;
abstract class Event
{
//
}

View File

@ -1,44 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Queue\SerializesModels;
/**
* Class OAuth2ClientLocked
* @package App\Events
*/
final class OAuth2ClientLocked
{
use SerializesModels;
/**
* @var string
*/
private $client_id;
/**
* OAuth2ClientLocked constructor.
* @param string $client_id
*/
public function __construct(string $client_id)
{
$this->client_id = $client_id;
}
/**
* @return string
*/
public function getClientId(): string
{
return $this->client_id;
}
}

View File

@ -1,19 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserActivated
* @package App\Events
*/
class UserActivated extends UserEvent {}

View File

@ -1,20 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Queue\SerializesModels;
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* Class UserCreated
* @package App\Events
*/
final class UserCreated extends UserEvent {}

View File

@ -1,19 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserDeactivated
* @package App\Events
*/
class UserDeactivated extends UserEvent {}

View File

@ -1,18 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserEmailUpdated
* @package App\Events
*/
class UserEmailUpdated extends UserEvent{}

View File

@ -1,18 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserEmailVerified
* @package App\Events
*/
final class UserEmailVerified extends UserEvent {}

View File

@ -1,44 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Queue\SerializesModels;
/**
* Class UserEvent
* @package App\Events
*/
abstract class UserEvent
{
use SerializesModels;
/**
* @var int
*/
protected $user_id;
/**
* UserEvent constructor.
* @param int $user_id
*/
public function __construct(int $user_id)
{
$this->user_id = $user_id;
}
/**
* @return int
*/
public function getUserId(): int
{
return $this->user_id;
}
}

View File

@ -1,18 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserLocked
* @package App\Events
*/
final class UserLocked extends UserEvent{}

View File

@ -1,18 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserPasswordResetRequestCreated
* @package App\Events
*/
final class UserPasswordResetRequestCreated extends UserEvent{}

View File

@ -1,18 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserPasswordResetSuccessful
* @package App\Events
*/
final class UserPasswordResetSuccessful extends UserEvent{}

View File

@ -1,22 +0,0 @@
<?php namespace App\Events;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserSpamStateUpdated
* @package App\Events
*/
class UserSpamStateUpdated extends UserEvent
{
}

View File

@ -1,64 +0,0 @@
<?php namespace App\Exceptions;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Predis\Connection\ConnectionException as RedisConnectionException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
/**
* Class Handler
* @package App\Exceptions
*/
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
RedisConnectionException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}

View File

@ -1,656 +0,0 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Utils\CountryList;
use App\libs\Auth\Repositories\IBannedIPRepository;
use App\libs\Auth\Repositories\IGroupRepository;
use Auth\Repositories\IUserRepository;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Redirect;
use OAuth2\Repositories\IAccessTokenRepository;
use OAuth2\Repositories\IApiEndpointRepository;
use OAuth2\Repositories\IApiRepository;
use OAuth2\Repositories\IApiScopeRepository;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Repositories\IRefreshTokenRepository;
use OAuth2\Repositories\IResourceServerRepository;
use OAuth2\Repositories\IApiScopeGroupRepository;
use OAuth2\Repositories\IServerPrivateKeyRepository;
use OAuth2\Services\IApiEndpointService;
use OAuth2\Services\IApiScopeService;
use OAuth2\Services\IApiService;
use OAuth2\Services\IClientService;
use OAuth2\Services\IResourceServerService;
use OpenId\Services\IUserService;
use Sokil\IsoCodes\IsoCodesFactory;
use utils\Filter;
use utils\FilterElement;
use utils\PagingInfo;
use Utils\Services\IAuthService;
use Utils\Services\IBannedIPService;
use Utils\Services\IServerConfigurationService;
use Illuminate\Support\Facades\Log;
/**
* Class AdminController
* @package App\Http\Controllers
*/
class AdminController extends Controller {
/**
* @var IClientService
*/
private $client_service;
/**
* @var IApiScopeService
*/
private $scope_service;
/**
* @var IAccessTokenRepository
*/
private $access_token_repository;
/**
* @var IRefreshTokenRepository
*/
private $refresh_token_repository;
/**
* @var IResourceServerService
*/
private $resource_server_service;
/**
* @var IApiService
*/
private $api_service;
/**
* @var IApiEndpointService
*/
private $endpoint_service;
/**
* @var IAuthService
*/
private $auth_service;
/**
* @var IUserService
*/
private $user_service;
/**
* @var IServerConfigurationService
*/
private $configuration_service;
/**
* @var IBannedIPService
*/
private $banned_ips_service;
/**
* @var IServerPrivateKeyRepository
*/
private $private_keys_repository;
/**
* @var IApiScopeGroupRepository
*/
private $api_group_repository;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IUserRepository
*/
private $user_repository;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var IApiScopeRepository
*/
private $scope_repository;
/**
* @var IApiRepository
*/
private $api_repository;
/**
* @var IResourceServerRepository
*/
private $resource_server_repository;
/**
* @var IGroupRepository
*/
private $group_repository;
/**
* @var IBannedIPRepository
*/
private $banned_ips_repository;
const TokenPageSize = 25;
/**
* AdminController constructor.
* @param IClientService $client_service
* @param IApiScopeService $scope_service
* @param IAccessTokenRepository $access_token_repository
* @param IRefreshTokenRepository $refresh_token_repository
* @param IResourceServerService $resource_server_service
* @param IApiService $api_service
* @param IApiEndpointService $endpoint_service
* @param IAuthService $auth_service
* @param IUserService $user_service
* @param IServerConfigurationService $configuration_service
* @param IBannedIPService $banned_ips_service
* @param IServerPrivateKeyRepository $private_keys_repository
* @param IApiScopeGroupRepository $api_group_repository
* @param IClientRepository $client_repository
* @param IUserRepository $user_repository
* @param IApiEndpointRepository $endpoint_repository
* @param IApiScopeRepository $scope_repository
* @param IApiRepository $api_repository
* @param IResourceServerRepository $resource_server_repository
* @param IBannedIPRepository $banned_ips_repository
* @param IGroupRepository $group_repository
*/
public function __construct(
IClientService $client_service,
IApiScopeService $scope_service,
IAccessTokenRepository $access_token_repository,
IRefreshTokenRepository $refresh_token_repository,
IResourceServerService $resource_server_service,
IApiService $api_service,
IApiEndpointService $endpoint_service,
IAuthService $auth_service,
IUserService $user_service,
IServerConfigurationService $configuration_service,
IBannedIPService $banned_ips_service,
IServerPrivateKeyRepository $private_keys_repository,
IApiScopeGroupRepository $api_group_repository,
IClientRepository $client_repository,
IUserRepository $user_repository,
IApiEndpointRepository $endpoint_repository,
IApiScopeRepository $scope_repository,
IApiRepository $api_repository,
IResourceServerRepository $resource_server_repository,
IBannedIPRepository $banned_ips_repository,
IGroupRepository $group_repository
)
{
$this->client_service = $client_service;
$this->scope_service = $scope_service;
$this->access_token_repository = $access_token_repository;
$this->refresh_token_repository = $refresh_token_repository;
$this->resource_server_service = $resource_server_service;
$this->api_service = $api_service;
$this->endpoint_service = $endpoint_service;
$this->auth_service = $auth_service;
$this->user_service = $user_service;
$this->configuration_service = $configuration_service;
$this->banned_ips_service = $banned_ips_service;
$this->private_keys_repository = $private_keys_repository;
$this->api_group_repository = $api_group_repository;
$this->client_repository = $client_repository;
$this->user_repository = $user_repository;
$this->endpoint_repository = $endpoint_repository;
$this->scope_repository = $scope_repository;
$this->api_repository = $api_repository;
$this->resource_server_repository = $resource_server_repository;
$this->banned_ips_repository = $banned_ips_repository;
$this->group_repository = $group_repository;
}
/**
* @param $id
* @return \Illuminate\Contracts\View\View
*/
public function editRegisteredClient($id)
{
$user = $this->auth_service->getCurrentUser();
$client = $this->client_repository->getClientByIdentifier($id);
if (is_null($client)) {
Log::warning(sprintf("invalid oauth2 client id %s", $id));
return View::make("errors.404");
}
$selected_scopes = $client->getClientScopes();
$aux_scopes = [];
foreach ($selected_scopes as $scope) {
array_push($aux_scopes, $scope->getId());
}
// scope pre processing
$scopes = $this->scope_repository->getAvailableScopes();
$group_scopes = $user->getGroupScopes();
$merged_scopes = array_merge($scopes, $group_scopes);
$final_scopes = [];
$processed_scopes = [];
foreach($merged_scopes as $test_scope){
if(isset($processed_scopes[$test_scope->getId()])) continue;
$processed_scopes[$test_scope->getId()] = $test_scope->getId();
$final_scopes[] = $test_scope;
}
usort($final_scopes, function($elem1, $elem2){
return $elem1->getApiId() > $elem2->getApiId() ;
});
// scope pre processing
$access_tokens = $this->access_token_repository->getAllValidByClientIdentifier($client->getId(), new PagingInfo(1 , self::TokenPageSize));
foreach ($access_tokens->getItems() as $token) {
$friendly_scopes = $this->scope_repository->getFriendlyScopesByName(explode(' ', $token->scope));
$token->setFriendlyScopes(implode(',', $friendly_scopes));
}
$refresh_tokens = $this->refresh_token_repository->getAllValidByClientIdentifier($client->getId(), new PagingInfo(1 , self::TokenPageSize));
foreach ($refresh_tokens->getItems() as $token) {
$friendly_scopes = $this->scope_repository->getFriendlyScopesByName(explode(' ', $token->scope));
$token->setFriendlyScopes(implode(',', $friendly_scopes));
}
return View::make("oauth2.profile.edit-client",
[
'client' => $client,
'selected_scopes' => $aux_scopes,
'scopes' => $final_scopes,
'access_tokens' => $access_tokens->getItems(),
'access_tokens_pages' => $access_tokens->getTotal() > 0 ? intval(ceil($access_tokens->getTotal() / self::TokenPageSize)) : 0,
"use_system_scopes" => $user->canUseSystemScopes(),
'refresh_tokens' => $refresh_tokens->getItems(),
'refresh_tokens_pages' => $refresh_tokens->getTotal() > 0 ? intval(ceil($refresh_tokens->getTotal() / self::TokenPageSize)) : 0,
]);
}
// Api Scope Groups
public function listApiScopeGroups()
{
$user = $this->auth_service->getCurrentUser();
$groups = $this->api_group_repository->getAllByPage(new PagingInfo(1, PHP_INT_MAX));
$non_selected_scopes = $this->scope_repository->getAssignableByGroups();
return View::make("oauth2.profile.admin.api-scope-groups", [
'groups' => $groups,
'non_selected_scopes' => $non_selected_scopes,
]);
}
/**
* @param $id
* @return \Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function editApiScopeGroup($id){
$group = $this->api_group_repository->getById($id);
if(is_null($group))
return Response::view('errors.404', [], 404);
$user = $this->auth_service->getCurrentUser();
$non_selected_scopes = $this->scope_repository->getAssignableByGroups();
return View::make("oauth2.profile.admin.edit-api-scope-group",
array
(
'group' => $group,
'non_selected_scopes' => $non_selected_scopes,
)
);
}
// Resource servers
/**
* @return \Illuminate\Contracts\View\View
*/
public function listResourceServers() {
$user = $this->auth_service->getCurrentUser();
$resource_servers = $this->resource_server_repository->getAllByPage(new PagingInfo(1, PHP_INT_MAX));
return View::make("oauth2.profile.admin.resource-servers",
[
'resource_servers' => $resource_servers
]
);
}
/**
* @param $id
* @return \Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function editResourceServer($id){
$resource_server = $this->resource_server_repository->getById($id);
if(is_null($resource_server))
return Response::view('errors.404', [], 404);
$user = $this->auth_service->getCurrentUser();
return View::make("oauth2.profile.admin.edit-resource-server",array(
'resource_server'=>$resource_server
));
}
/**
* @param $id
* @return \Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function editApi($id){
$api = $this->api_repository->getById($id);
if(is_null($api))
return Response::view('errors.404', [], 404);
$user = $this->auth_service->getCurrentUser();
return View::make("oauth2.profile.admin.edit-api",['api'=>$api]);
}
/**
* @param $id
* @return \Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function editScope($id){
$scope = $this->scope_repository->getById($id);
if(is_null($scope))
return Response::view('errors.404', [], 404);
$user = $this->auth_service->getCurrentUser();
return View::make("oauth2.profile.admin.edit-scope",array(
'scope'=>$scope));
}
/**
* @param $id
* @return \Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function editEndpoint($id){
$endpoint = $this->endpoint_repository->getById($id);
if(is_null($endpoint)) return Response::view('errors.404', [], 404);
$user = $this->auth_service->getCurrentUser();
$selected_scopes = [];
$list = $endpoint->getScopes();
foreach($list as $selected_scope){
$selected_scopes[] = $selected_scope->getId();
}
return View::make('oauth2.profile.admin.edit-endpoint',array(
'endpoint' => $endpoint ,
'selected_scopes' => $selected_scopes));
}
/**
* @return \Illuminate\Contracts\View\View
*/
public function editIssuedGrants(){
$user = $this->auth_service->getCurrentUser();
$access_tokens = $this->access_token_repository->getAllValidByUserId($user->getId(), new PagingInfo(1, self::TokenPageSize));
$refresh_tokens = $this->refresh_token_repository->getAllValidByUserId($user->getId(), new PagingInfo(1, self::TokenPageSize));
foreach($access_tokens->getItems() as $access_token){
$friendly_scopes = $this->scope_repository->getFriendlyScopesByName(explode(' ',$access_token->getScope()));
$access_token->setFriendlyScopes(implode(', ',$friendly_scopes));
}
foreach($refresh_tokens->getItems() as $refresh_token){
$friendly_scopes = $this->scope_repository->getFriendlyScopesByName(explode(' ',$refresh_token->getScope()));
$refresh_token->setFriendlyScopes(implode(', ',$friendly_scopes));
}
return View::make("oauth2.profile.edit-user-grants",
array
(
'user_id' => $user->getId(),
'access_tokens' => $access_tokens->getItems() ,
'access_tokens_pages' => $access_tokens->getTotal() > 0 ? intval(ceil($access_tokens->getTotal() / self::TokenPageSize)) : 0,
'refresh_tokens' => $refresh_tokens->getItems(),
'refresh_tokens_pages' => $refresh_tokens->getTotal() > 0 ? intval(ceil($refresh_tokens->getTotal() / self::TokenPageSize)) : 0,
)
);
}
/**
* @return \Illuminate\Contracts\View\View
*/
public function listOAuth2Clients(){
$user = $this->auth_service->getCurrentUser();
$clients = $user->getAvailableClients();
return View::make("oauth2.profile.clients", [
"username" => $user->getFullName(),
"user_id" => $user->getId(),
"use_system_scopes" => $user->canUseSystemScopes(),
'clients' => $clients,
]);
}
/**
* @return \Illuminate\Contracts\View\View
*/
public function listLockedClients(){
$filter = new Filter();
$filter->addFilterCondition(FilterElement::makeEqual('locked', true));
$clients = $this->client_repository->getAllByPage(new PagingInfo(1, PHP_INT_MAX), $filter);
return View::make("oauth2.profile.admin.clients",[
'clients' => $clients
]);
}
public function listServerConfig(){
$user = $this->auth_service->getCurrentUser();
$config_values = [];
$dictionary = array
(
'MaxFailed.Login.Attempts',
'MaxFailed.LoginAttempts.2ShowCaptcha',
'OpenId.Private.Association.Lifetime',
'OpenId.Session.Association.Lifetime',
'OpenId.Nonce.Lifetime',
'OAuth2.AuthorizationCode.Lifetime',
'OAuth2.AccessToken.Lifetime',
'OAuth2.IdToken.Lifetime',
'OAuth2.RefreshToken.Lifetime',
'OAuth2.AccessToken.Revoked.Lifetime',
'OAuth2.AccessToken.Void.Lifetime',
'OAuth2.RefreshToken.Revoked.Lifetime',
'OAuth2SecurityPolicy.MaxBearerTokenDisclosureAttempts',
'OAuth2SecurityPolicy.MinutesWithoutExceptions',
'OAuth2SecurityPolicy.MaxInvalidClientExceptionAttempts',
'OAuth2SecurityPolicy.MaxInvalidRedeemAuthCodeAttempts',
'OAuth2SecurityPolicy.MaxInvalidClientCredentialsAttempts',
);
foreach($dictionary as $key)
$config_values[$key] = $this->configuration_service->getConfigValue($key);
return View::make("admin.server-config",
array
(
"username" => $user->getFullName(),
"user_id" => $user->getId(),
'config_values' => $config_values,
)
);
}
public function saveServerConfig(){
$values = Input::all();
$rules = array
(
'general-max-failed-login-attempts' => 'required|integer',
'general-max-failed-login-attempts-captcha' => 'required|integer',
'openid-private-association-lifetime' => 'required|integer',
'openid-session-association-lifetime' => 'required|integer',
'openid-nonce-lifetime' => 'required|integer',
'oauth2-auth-code-lifetime' => 'required|integer',
'oauth2-refresh-token-lifetime' => 'required|integer',
'oauth2-access-token-lifetime' => 'required|integer',
'oauth2-id-token-lifetime' => 'required|integer',
'oauth2-id-access-token-revoked-lifetime' => 'required|integer',
'oauth2-id-access-token-void-lifetime' => 'required|integer',
'oauth2-id-refresh-token-revoked-lifetime' => 'required|integer',
'oauth2-id-security-policy-minutes-without-exceptions' => 'required|integer',
'oauth2-id-security-policy-max-bearer-token-disclosure-attempts' => 'required|integer',
'oauth2-id-security-policy-max-invalid-client-exception-attempts' => 'required|integer',
'oauth2-id-security-policy-max-invalid-redeem-auth-code-attempts' => 'required|integer',
'oauth2-id-security-policy-max-invalid-client-credentials-attempts' => 'required|integer',
);
$dictionary = array
(
'general-max-failed-login-attempts' => 'MaxFailed.Login.Attempts',
'general-max-failed-login-attempts-captcha' => 'MaxFailed.LoginAttempts.2ShowCaptcha',
'openid-private-association-lifetime' => 'OpenId.Private.Association.Lifetime',
'openid-session-association-lifetime' => 'OpenId.Session.Association.Lifetime',
'openid-nonce-lifetime' => 'OpenId.Nonce.Lifetime',
'oauth2-auth-code-lifetime' => 'OAuth2.AuthorizationCode.Lifetime',
'oauth2-access-token-lifetime' => 'OAuth2.AccessToken.Lifetime',
'oauth2-id-token-lifetime' => 'OAuth2.IdToken.Lifetime',
'oauth2-refresh-token-lifetime' => 'OAuth2.RefreshToken.Lifetime',
'oauth2-id-access-token-revoked-lifetime' => 'OAuth2.AccessToken.Revoked.Lifetime',
'oauth2-id-access-token-void-lifetime' => 'OAuth2.AccessToken.Void.Lifetime',
'oauth2-id-refresh-token-revoked-lifetime' => 'OAuth2.RefreshToken.Revoked.Lifetime',
'oauth2-id-security-policy-minutes-without-exceptions' => 'OAuth2SecurityPolicy.MinutesWithoutExceptions',
'oauth2-id-security-policy-max-bearer-token-disclosure-attempts' => 'OAuth2SecurityPolicy.MaxBearerTokenDisclosureAttempts',
'oauth2-id-security-policy-max-invalid-client-exception-attempts' => 'OAuth2SecurityPolicy.MaxInvalidClientExceptionAttempts',
'oauth2-id-security-policy-max-invalid-redeem-auth-code-attempts' => 'OAuth2SecurityPolicy.MaxInvalidRedeemAuthCodeAttempts',
'oauth2-id-security-policy-max-invalid-client-credentials-attempts' => 'OAuth2SecurityPolicy.MaxInvalidClientCredentialsAttempts',
);
// Creates a Validator instance and validates the data.
$validation = Validator::make($values, $rules);
if ($validation->fails())
{
return Redirect::action("AdminController@listServerConfig")->withErrors($validation);
}
foreach($values as $field => $value)
{
if(array_key_exists($field, $dictionary))
$this->configuration_service->saveConfigValue($dictionary[$field], $value);
}
return Redirect::action("AdminController@listServerConfig");
}
public function listBannedIPs(){
$page = $this->banned_ips_repository->getAllByPage(new PagingInfo(1, PHP_INT_MAX));
return View::make("admin.banned-ips",[
"page" => $page
]
);
}
public function listServerPrivateKeys(){
return View::make("oauth2.profile.admin.server-private-keys",
[
'private_keys' => $this->private_keys_repository->getAllByPage(new PagingInfo(1, PHP_INT_MAX)),
]
);
}
public function listUsers(){
// init database
$isoCodes = new IsoCodesFactory();
// get languages database
$languages = $isoCodes->getLanguages()->toArray();
$lang2Code = [];
foreach ($languages as $lang){
if(!empty($lang->getAlpha2()))
$lang2Code[] = $lang;
}
// get countries database
$countries = $isoCodes->getCountries()->toArray();
return View::make("admin.users",
[
'page' => $this->user_repository->getAllByPage(new PagingInfo(1, 10)),
'countries' => CountryList::getCountries(),
]
);
}
public function listGroups(){
return View::make("admin.groups",
[
'groups' => $this->group_repository->getAllByPage(new PagingInfo(1, 10)),
]
);
}
/**
* @param $user_id
* @return \Illuminate\Contracts\View\View
*/
public function editUser($user_id){
$user = $this->user_repository->getById($user_id);
if (is_null($user)) {
Log::warning(sprintf("invalid user id %s", $user_id));
return View::make("errors.404");
}
// init database
$isoCodes = new IsoCodesFactory();
// get languages database
$languages = $isoCodes->getLanguages()->toArray();
$lang2Code = [];
foreach ($languages as $lang){
if(!empty($lang->getAlpha2()))
$lang2Code[] = $lang;
}
return View::make("admin.edit-user",
[
'user' => $user,
'countries' => CountryList::getCountries(),
'languages' => $lang2Code,
]
);
}
/**
* @param $group_id
* @return \Illuminate\Contracts\View\View
*/
public function editGroup($group_id){
$group = $this->group_repository->getById($group_id);
if (is_null($group)) {
Log::warning(sprintf("invalid group id %s", $group_id));
return View::make("errors.404");
}
return View::make("admin.edit-group",
[
'group' => $group,
]
);
}
}

View File

@ -1,249 +0,0 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Api\JsonController;
use App\Http\Utils\PagingConstants;
use App\ModelSerializers\SerializerRegistry;
use App\Services\IBaseService;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use models\utils\IBaseRepository;
use utils\Filter;
use utils\FilterParser;
use utils\OrderParser;
use utils\PagingInfo;
use Utils\Services\ILogService;
use Exception;
use models\exceptions\ValidationException;
use models\exceptions\EntityNotFoundException;
/**
* Class APICRUDController
* @package App\Http\Controllers
*/
abstract class APICRUDController extends JsonController
{
use GetAllTrait;
/**
* @var IBaseRepository
*/
protected $repository;
/**
* @var IBaseService
*/
protected $service;
/**
* @param IBaseRepository $repository
* @param IBaseService $service
* @param ILogService $log_service
*/
public function __construct
(
IBaseRepository $repository,
IBaseService $service,
ILogService $log_service
)
{
parent::__construct($log_service);
$this->repository = $repository;
$this->service = $service;
}
/**
* @param $id
* @return string
*/
protected function getEntityNotFoundMessage($id):string {
return sprintf("entity %s not found", $id);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse
*/
public function get($id)
{
try {
$entity = $this->repository->getById($id);
if (is_null($entity)) {
throw new EntityNotFoundException($this->getEntityNotFoundMessage($id));
}
return $this->ok(SerializerRegistry::getInstance()->getSerializer($entity, $this->serializerType())->serialize
(
Input::get("expand", '')
));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
protected function serializerType():string{
return SerializerRegistry::SerializerType_Public;
}
/**
* @return array
*/
protected abstract function getUpdatePayloadValidationRules():array;
/**
* @return array
*/
protected function getUpdatePayload():array{
return request()->all();
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function update($id)
{
$payload = $this->getUpdatePayload();
return $this->_update($id, $payload);
}
protected function curateUpdatePayload(array $payload):array {
return $payload;
}
protected function curateCreatePayload(array $payload):array {
return $payload;
}
protected function onUpdate($id, $payload){
return $this->service->update($id, $payload);
}
/**
* @param $id
* @param array $payload
* @return \Illuminate\Http\JsonResponse|mixed
*/
protected function _update($id, array $payload)
{
try {
$rules = $this->getUpdatePayloadValidationRules();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
$entity = $this->onUpdate($id, $this->curateUpdatePayload($payload));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity, $this->serializerType())->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected abstract function getCreatePayloadValidationRules():array;
/**
* @return array
*/
protected function getCreatePayload():array{
return Input::All();
}
/**
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function create()
{
try {
$payload = $this->getCreatePayload();
$rules = $this->getCreatePayloadValidationRules();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
$entity = $this->service->create($this->curateCreatePayload($payload));
return $this->created(SerializerRegistry::getInstance()->getSerializer($entity, $this->serializerType())->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function delete($id)
{
try {
$this->service->delete($id);
return $this->deleted();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,133 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\libs\Auth\Repositories\IBannedIPRepository;
use App\ModelSerializers\SerializerRegistry;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use Utils\Services\IBannedIPService;
use Utils\Services\ILogService;
use Illuminate\Support\Facades\Input;
use Exception;
/**
* Class ApiBannedIPController
* @package App\Http\Controllers\Api
*/
final class ApiBannedIPController extends APICRUDController
{
/**
* ApiBannedIPController constructor.
* @param IBannedIPRepository $banned_ip_repository
* @param IBannedIPService $banned_ip_service
* @param ILogService $log_service
*/
public function __construct
(
IBannedIPRepository $banned_ip_repository,
IBannedIPService $banned_ip_service,
ILogService $log_service
)
{
parent::__construct($banned_ip_repository, $banned_ip_service, $log_service);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function get($id)
{
try {
$ip = Input::get("ip", null);
if (!is_null($ip)) {
$banned_ip = $this->repository->getByIp(strval($ip));
} else {
$banned_ip = $this->repository->getById(intval($id));
}
if (is_null($banned_ip)) {
throw new EntityNotFoundException();
}
return $this->ok(SerializerRegistry::getInstance()->getSerializer($banned_ip)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param null $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function delete($id = null)
{
try {
if (is_null($id)) {
$ip = Input::get("ip", null);
} else {
$banned_ip = $this->repository->getById($id);
$ip = $banned_ip->getIp();
}
if (is_null($ip))
return $this->error400('invalid request');
$this->service->deleteByIP($ip);
return $this->deleted();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [];
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [];
}
}

View File

@ -1,133 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\ModelSerializers\SerializerRegistry;
use Exception;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\Repositories\IApiRepository;
use OAuth2\Services\IApiService;
use Utils\Services\ILogService;
/**
* Class ApiController
* @package App\Http\Controllers\Api
*/
final class ApiController extends APICRUDController
{
/**
* ApiController constructor.
* @param IApiRepository $api_repository
* @param IApiService $api_service
* @param ILogService $log_service
*/
public function __construct
(
IApiRepository $api_repository,
IApiService $api_service,
ILogService $log_service
)
{
parent::__construct($api_repository, $api_service, $log_service);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function activate($id)
{
try {
$api = $this->service->update($id, ['active' => true]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($api)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected function getFilterRules():array{
return [
'resource_server_id' => ['==']
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'resource_server_id' => 'sometimes|required|integer',
];
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deactivate($id)
{
try {
$api = $this->service->update($id, ['active' => false]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($api)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [
'name' => 'sometimes|required|alpha_dash|max:255',
'description' => 'sometimes|required|text',
'active' => 'sometimes|required|boolean',
];
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'name' => 'required|alpha_dash|max:255',
'description' => 'required|text',
'active' => 'required|boolean',
'resource_server_id' => 'required|integer',
];
}
}

View File

@ -1,185 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\ModelSerializers\SerializerRegistry;
use Exception;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\Repositories\IApiEndpointRepository;
use OAuth2\Services\IApiEndpointService;
use Utils\Services\ILogService;
/**
* Class ApiEndpointController
* REST Controller for Api endpoint entity CRUD ops
*/
final class ApiEndpointController extends APICRUDController {
/**
* ApiEndpointController constructor.
* @param IApiEndpointService $api_endpoint_service
* @param IApiEndpointRepository $endpoint_repository
* @param ILogService $log_service
*/
public function __construct
(
IApiEndpointService $api_endpoint_service,
IApiEndpointRepository $endpoint_repository,
ILogService $log_service
)
{
parent::__construct($endpoint_repository, $api_endpoint_service, $log_service);
}
public function activate($id){
try {
$endpoint = $this->service->update($id,['active'=>false]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($endpoint)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function deactivate($id){
try {
$endpoint = $this->service->update($id,['active'=>false]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($endpoint)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function addRequiredScope($id, $scope_id){
try {
$endpoint = $this->service->addRequiredScope($id, $scope_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($endpoint)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function removeRequiredScope($id, $scope_id){
try {
$endpoint = $this->service->removeRequiredScope($id,$scope_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($endpoint)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
'http_method' => ['=@', '=='],
'route' => ['=@', '=='],
'active' => [ '=='],
'api_id' => ['=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
'http_method'=> 'sometimes|required|string',
'route' => 'sometimes|required|string',
'active' => 'sometimes|required|boolean',
'api_id' => 'sometimes|required|integer',
];
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [
'name' => 'required|alpha_dash|max:255',
'description' => 'required|freetext',
'active' => 'required|boolean',
'allow_cors' => 'required|boolean',
'route' => 'required|route',
'http_method' => 'required|httpmethod',
'api_id' => 'required|integer',
'rate_limit' => 'required|integer',
];
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'name' => 'sometimes|required|alpha_dash|max:255',
'description' => 'sometimes|required|freetext',
'active' => 'sometimes|required|boolean',
'allow_cors' => 'sometimes|required|boolean',
'route' => 'sometimes|required|route',
'http_method' => 'sometimes|required|httpmethod',
'rate_limit' => 'sometimes|integer',
];
}
}

View File

@ -1,138 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\ModelSerializers\SerializerRegistry;
use Exception;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\Repositories\IResourceServerRepository;
use OAuth2\Services\IResourceServerService;
use Utils\Services\ILogService;
/**
* Class ApiResourceServerController
* @package App\Http\Controllers\Api
*/
final class ApiResourceServerController extends APICRUDController
{
/**
* ApiResourceServerController constructor.
* @param IResourceServerRepository $repository
* @param IResourceServerService $resource_server_service
* @param ILogService $log_service
*/
public function __construct
(
IResourceServerRepository $repository,
IResourceServerService $resource_server_service,
ILogService $log_service
)
{
parent::__construct($repository, $resource_server_service, $log_service);
}
public function regenerateClientSecret($id)
{
try {
$resource_server = $this->service->regenerateClientSecret($id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($resource_server->getClient())->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function activate($id)
{
try {
$entity = $this->service->update($id, ['active' => true]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function deactivate($id)
{
try {
$entity = $this->service->update($id, ['active' => false]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [
'host' => 'sometimes|required|host|max:255',
'ips' => 'required',
'friendly_name' => 'sometimes|required|text|max:512',
];
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'host' => 'required|host|max:255',
'ips' => 'required',
'friendly_name' => 'required|text|max:512',
'active' => 'required|boolean',
];
}
}

View File

@ -1,140 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\ModelSerializers\SerializerRegistry;
use Exception;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\Repositories\IApiScopeRepository;
use OAuth2\Services\IApiScopeService;
use Utils\Services\ILogService;
/**
* Class ApiScopeController
*/
final class ApiScopeController extends APICRUDController
{
public function __construct
(
IApiScopeRepository $scope_repository,
IApiScopeService $api_scope_service,
ILogService $log_service
)
{
parent::__construct($scope_repository, $api_scope_service, $log_service);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function activate($id)
{
try {
$scope = $this->service->update($id, ['active' => true]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($scope)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deactivate($id)
{
try {
$scope = $this->service->update($id, ['active' => false]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($scope)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [
'id' => 'required|integer',
'name' => 'sometimes|required|scopename|max:512',
'description' => 'sometimes|required|freetext',
'short_description' => 'sometimes|required|freetext|max:512',
'active' => 'sometimes|required|boolean',
'system' => 'sometimes|required|boolean',
'default' => 'sometimes|required|boolean',
'assigned_by_groups' => 'sometimes|boolean',
];
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'name' => 'required|scopename|max:512',
'short_description' => 'required|freetext|max:512',
'description' => 'required|freetext',
'active' => 'required|boolean',
'default' => 'required|boolean',
'system' => 'required|boolean',
'api_id' => 'required|integer',
'assigned_by_groups' => 'required|boolean',
];
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
'is_assigned_by_groups' => ['=='],
'api_id' => ['=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
'is_assigned_by_groups' => 'sometimes|required|boolean',
'api_id' => 'sometimes|required|integer',
];
}
}

View File

@ -1,123 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\ModelSerializers\SerializerRegistry;
use Exception;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\Repositories\IApiScopeGroupRepository;
use OAuth2\Services\IApiScopeGroupService;
use Utils\Services\ILogService;
/**
* Class ApiScopeGroupController
* @package App\Http\Controllers
*/
final class ApiScopeGroupController extends APICRUDController
{
/**
* ApiScopeGroupController constructor.
* @param IApiScopeGroupService $service
* @param IApiScopeGroupRepository $repository
* @param ILogService $log_service
*/
public function __construct
(
IApiScopeGroupService $service,
IApiScopeGroupRepository $repository,
ILogService $log_service
)
{
parent::__construct($repository, $service, $log_service);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function activate($id){
try
{
$entity = $this->service->update($id, ['active' => true]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deactivate($id){
try
{
$entity = $this->service->update($id, ['active' => false]);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [
'name' => 'required|text|max:512',
'active' => 'required|boolean',
'scopes' => 'required',
'users' => 'required|user_ids',
];
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'name' => 'required|text|max:512',
'active' => 'required|boolean',
'scopes' => 'required',
'users' => 'required|user_ids',
];
}
}

View File

@ -1,63 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use OAuth2\Services\IAsymmetricKeyService;
use models\exceptions\EntityNotFoundException;
use Utils\Services\ILogService;
use OAuth2\Repositories\IAsymmetricKeyRepository;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Exception;
/**
* Class AsymmetricKeyApiController
* @package App\Http\Controllers\Api
*/
abstract class AsymmetricKeyApiController extends APICRUDController
{
/**
* @var IAsymmetricKeyService
*/
protected $service;
/**
* @var IAsymmetricKeyRepository
*/
protected $repository;
/**
* @param IAsymmetricKeyRepository $repository
* @param IAsymmetricKeyService $service
* @param ILogService $log_service
*/
public function __construct(
IAsymmetricKeyRepository $repository,
IAsymmetricKeyService $service,
ILogService $log_service
) {
parent::__construct($repository, $service, $log_service);
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [
'id' => 'required|integer',
'active' => 'required|boolean',
];
}
}

View File

@ -1,695 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\Http\Utils\PagingConstants;
use App\ModelSerializers\SerializerRegistry;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use OAuth2\Repositories\IAccessTokenRepository;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Repositories\IRefreshTokenRepository;
use OAuth2\Services\ITokenService;
use OAuth2\Services\IApiScopeService;
use OAuth2\Services\IClientService;
use utils\Filter;
use utils\FilterElement;
use utils\PagingInfo;
use Utils\Services\IAuthService;
use Utils\Services\ILogService;
use models\exceptions\ValidationException;
use Illuminate\Support\Facades\Log;
/**
* Class ClientApiController
* @package App\Http\Controllers\Api
*/
final class ClientApiController extends APICRUDController
{
/**
* @var IApiScopeService
*/
private $scope_service;
/**
* @var ITokenService
*/
private $token_service;
/**
* @var IAuthService
*/
private $auth_service;
/**
* @var IAccessTokenRepository
*/
private $access_token_repository;
/**
* @var IRefreshTokenRepository
*/
private $refresh_token_repository;
/**
* ClientApiController constructor.
* @param IApiScopeService $scope_service
* @param ITokenService $token_service
* @param IClientService $client_service
* @param IAuthService $auth_service
* @param ILogService $log_service
* @param IClientRepository $client_repository
* @param IAccessTokenRepository $access_token_repository
* @param IRefreshTokenRepository $refresh_token_repository
*/
public function __construct
(
IApiScopeService $scope_service,
ITokenService $token_service,
IClientService $client_service,
IAuthService $auth_service,
ILogService $log_service,
IClientRepository $client_repository,
IAccessTokenRepository $access_token_repository,
IRefreshTokenRepository $refresh_token_repository
)
{
parent::__construct($client_repository, $client_service, $log_service);
$this->scope_service = $scope_service;
$this->token_service = $token_service;
$this->auth_service = $auth_service;
$this->access_token_repository = $access_token_repository;
$this->refresh_token_repository = $refresh_token_repository;
}
/**
* @param $id
* @param $scope_id
* @return mixed
*/
public function addAllowedScope($id, $scope_id)
{
try
{
$client = $this->service->addClientScope($id, $scope_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($client)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessages()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @param $scope_id
* @return mixed
*/
public function removeAllowedScope($id, $scope_id)
{
try
{
$client = $this->service->deleteClientScope($id, $scope_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($client)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessages()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
protected function applyExtraFilters(Filter $filter):Filter{
$current_user = Auth::user();
if(!is_null($current_user))
$filter->addFilterCondition(FilterElement::makeEqual("user_id", $current_user->getId()));
$filter->addFilterCondition(FilterElement::makeEqual('resource_server_not_set', true));
return $filter;
}
/**
* @param $id
* @return mixed
*/
public function activate($id)
{
try {
$client = $this->service->activateClient($id, true);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($client)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function deactivate($id)
{
try {
$client = $this->service->activateClient($id, false);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($client)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function regenerateClientSecret($id)
{
try
{
$client = $this->service->regenerateClientSecret($id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($client)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @param $use_refresh_token
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function setRefreshTokenClient($id, $use_refresh_token)
{
try {
$use_refresh_token = strtolower($use_refresh_token);
$use_refresh_token = ( $use_refresh_token == "false" || $use_refresh_token == "0") ? false : true;
$client = $this->service->setRefreshTokenUsage($id, $use_refresh_token);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($client)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @param $rotate_refresh_token
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function setRotateRefreshTokenPolicy($id, $rotate_refresh_token)
{
try {
$rotate_refresh_token = strtolower($rotate_refresh_token);
$rotate_refresh_token = ($rotate_refresh_token == "false" || $rotate_refresh_token == "0") ? false : true;
$client = $this->service->setRotateRefreshTokenPolicy($id, $rotate_refresh_token);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($client)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @param $value
* @param $hint
* @return mixed
*/
public function revokeToken($id, $value, $hint)
{
try {
$client = $this->repository->getClientByIdentifier($id);
if(is_null($client))
throw new EntityNotFoundException();
switch ($hint) {
case 'access-token': {
$token = $this->token_service->getAccessToken($value, true);
if (is_null($token)) {
throw new EntityNotFoundException();
}
if ($token->getClientId() !== $client->getClientId()) {
throw new ValidationException(sprintf('access token %s does not belongs to client id !', $value, $id));
}
$this->token_service->revokeAccessToken($value, true);
}
break;
case 'refresh-token': {
$token = $this->token_service->getRefreshToken($value, true);
if (is_null($token)) {
throw new EntityNotFoundException();
}
if ($token->getClientId() !== $client->getClientId()) {
throw new ValidationException(sprintf('refresh token %s does not belongs to client id !', $value, $id));
}
$this->token_service->revokeRefreshToken($value, true);
}
break;
default:
break;
}
return $this->ok();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function getAccessTokens($id)
{
$values = Input::all();
$rules = [
'page' => 'integer|min:1',
'per_page' => sprintf('required_with:page|integer|min:%s|max:%s', PagingConstants::MinPageSize, PagingConstants::MaxPageSize),
];
try {
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = PagingConstants::DefaultPageSize;;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$client = $this->repository->getClientByIdentifier($id);
if(is_null($client))
throw new EntityNotFoundException();
$data = $this->access_token_repository->getAllValidByClientIdentifier($id, new PagingInfo($page, $per_page));
return $this->ok
(
$data->toArray
(
Request::input('expand', ''),
[],
[],
[]
)
);
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function getRefreshTokens($id)
{
$values = Input::all();
$rules = [
'page' => 'integer|min:1',
'per_page' => sprintf('required_with:page|integer|min:%s|max:%s', PagingConstants::MinPageSize, PagingConstants::MaxPageSize),
];
try {
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = PagingConstants::DefaultPageSize;;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$client = $this->repository->getClientByIdentifier($id);
if(is_null($client))
throw new EntityNotFoundException();
$data = $this->refresh_token_repository->getAllValidByClientIdentifier($id, new PagingInfo($page, $per_page));
return $this->ok
(
$data->toArray
(
Request::input('expand', ''),
[],
[],
[]
)
);
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function getAccessTokensByCurrentUser()
{
$values = Input::all();
$rules = [
'page' => 'integer|min:1',
'per_page' => sprintf('required_with:page|integer|min:%s|max:%s', PagingConstants::MinPageSize, PagingConstants::MaxPageSize),
];
try {
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = PagingConstants::DefaultPageSize;;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$user = $this->auth_service->getCurrentUser();
$data = $this->access_token_repository->getAllValidByUserId($user->getId(), new PagingInfo($page, $per_page));
return $this->ok
(
$data->toArray
(
Request::input('expand', ''),
[],
[],
[]
)
);
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function getRefreshTokensByCurrentUser()
{
$values = Input::all();
$rules = [
'page' => 'integer|min:1',
'per_page' => sprintf('required_with:page|integer|min:%s|max:%s', PagingConstants::MinPageSize, PagingConstants::MaxPageSize),
];
try {
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = PagingConstants::DefaultPageSize;;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$user = $this->auth_service->getCurrentUser();
$data = $this->refresh_token_repository->getAllValidByUserId($user->getId(), new PagingInfo($page, $per_page));
return $this->ok
(
$data->toArray
(
Request::input('expand', ''),
[],
[],
[]
)
);
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function unlock($id)
{
try {
$client = $this->service->unlockClient($id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($client)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [
//'application_type' => 'required|application_type',
'app_name' => 'sometimes|required|freetext|max:255',
'app_description' => 'sometimes|required|freetext|max:512',
'website' => 'nullable|url',
'active' => 'sometimes|required|boolean',
'locked' => 'sometimes|required|boolean',
'use_refresh_token' => 'sometimes|required|boolean',
'rotate_refresh_token' => 'sometimes|required|boolean',
'contacts' => 'nullable|email_set',
'logo_uri' => 'nullable|url',
'tos_uri' => 'nullable|url',
'redirect_uris' => 'nullable|custom_url_set:application_type',
'policy_uri' => 'nullable|url',
'post_logout_redirect_uris' => 'nullable|ssl_url_set',
'allowed_origins' => 'nullable|ssl_url_set',
'logout_uri' => 'nullable|url',
'logout_session_required' => 'sometimes|required|boolean',
'logout_use_iframe' => 'sometimes|required|boolean',
'jwks_uri' => 'nullable|url',
'default_max_age' => 'sometimes|required|integer',
'require_auth_time' => 'sometimes|required|boolean',
'token_endpoint_auth_method' => 'sometimes|required|token_endpoint_auth_method',
'token_endpoint_auth_signing_alg' => 'sometimes|required|signing_alg',
'subject_type' => 'sometimes|required|subject_type',
'userinfo_signed_response_alg' => 'sometimes|required|signing_alg',
'userinfo_encrypted_response_alg' => 'sometimes|required|encrypted_alg',
'userinfo_encrypted_response_enc' => 'sometimes|required|encrypted_enc',
'id_token_signed_response_alg' => 'sometimes|required|signing_alg',
'id_token_encrypted_response_alg' => 'sometimes|required|encrypted_alg',
'id_token_encrypted_response_enc' => 'sometimes|required|encrypted_enc',
'admin_users' => 'nullable|int_array',
];
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'app_name' => 'required|freetext|max:255',
'app_description' => 'required|freetext|max:512',
'application_type' => 'required|applicationtype',
'website' => 'nullable|url',
'admin_users' => 'nullable|int_array',
];
}
}

View File

@ -1,95 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Services\IClientPublicKeyService;
use Utils\Services\ILogService;
use OAuth2\Repositories\IClientPublicKeyRepository;
use Illuminate\Support\Facades\Input;
/**
* Class ClientPublicKeyApiController
* @package App\Http\Controllers\Api
*/
final class ClientPublicKeyApiController extends AsymmetricKeyApiController
{
/**
* @param IClientPublicKeyRepository $repository
* @param IClientPublicKeyService $service
* @param ILogService $log_service
*/
public function __construct
(
IClientPublicKeyRepository $repository,
IClientPublicKeyService $service,
ILogService $log_service
)
{
parent::__construct($repository, $service, $log_service);
}
/**
* @return array
*/
protected function getCreatePayload():array{
$payload = Input::All();
return array_merge($payload, $this->extra_create_payload_params);
}
private $extra_create_payload_params = [];
/**
* @param int $client_id
* @return mixed
*/
public function _create($client_id)
{
$this->extra_create_payload_params['client_id'] = $client_id;
return $this->create();
}
/**
* @param int $client_id
* @param int $public_key_id
* @return mixed
*/
public function _update($client_id, $public_key_id)
{
return $this->update($public_key_id);
}
/**
* @param int $client_id
* @param int $public_key_id
* @return mixed
*/
public function _delete($client_id, $public_key_id){
return $this->delete($public_key_id);
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'client_id' => 'required|integer',
'kid' => 'required|text|max:255',
'active' => 'required|boolean',
'valid_from' => 'required|date_format:m/d/Y',
'valid_to' => 'required|date_format:m/d/Y|after:valid_from',
'pem_content' => 'required|public_key_pem|public_key_pem_length',
'usage' => 'required|public_key_usage',
'type' => 'required|public_key_type',
'alg' => 'required|key_alg:usage',
];
}
}

View File

@ -1,271 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\Http\Utils\PagingConstants;
use App\libs\Auth\Repositories\IGroupRepository;
use App\ModelSerializers\SerializerRegistry;
use App\Services\Auth\IGroupService;
use Auth\Repositories\IUserRepository;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use utils\Filter;
use utils\FilterElement;
use utils\FilterParser;
use utils\OrderParser;
use Utils\Services\ILogService;
use utils\PagingInfo;
use Exception;
/**
* Class GroupApiController
* @package App\Http\Controllers\Api
*/
final class GroupApiController extends APICRUDController
{
/**
* @var IUserRepository
*/
private $user_repository;
public function __construct
(
IGroupRepository $repository,
IUserRepository $user_repository,
IGroupService $service,
ILogService $log_service
)
{
parent::__construct($repository, $service, $log_service);
$this->user_repository = $user_repository;
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
'slug' => ['=@', '=='],
'active' => [ '=='],
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
'slug'
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array
{
return [
'name' => 'sometimes|required|string',
'slug' => 'sometimes|required|string',
'active' => 'sometimes|required|boolean',
];
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return [
'name' => 'sometimes|required|string|max:512',
'slug' => 'sometimes|alpha_dash|string|max:254',
'active' => 'sometimes|required|boolean',
'default' => 'sometimes|required|boolean',
];
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'name' => 'required|string|max:512',
'slug' => 'required|alpha_dash|max:254',
'active' => 'required|boolean',
'default' => 'required|boolean',
];
}
/**
* @param $group_id
* @param $user_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addUserToGroup($group_id, $user_id){
try {
$group = $this->repository->getById($group_id);
if(is_null($group))
return $this->error404();
$this->service->addUser2Group($group, $user_id);
return $this->updated();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $group_id
* @param $user_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeUserFromGroup($group_id, $user_id){
try {
$group = $this->repository->getById($group_id);
if(is_null($group))
return $this->error404();
$this->service->removeUserFromGroup($group, $user_id);
return $this->deleted();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $group_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getUsersFromGroup($group_id)
{
$values = Input::all();
$rules = [
'page' => 'integer|min:1',
'per_page' => sprintf('required_with:page|integer|min:%s|max:%s', PagingConstants::MinPageSize, PagingConstants::MaxPageSize),
];
try {
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = PagingConstants::DefaultPageSize;;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), [
'first_name' => ['=@', '=='],
'last_name' => ['=@', '=='],
'email' => ['=@', '=='],
'full_name' => ['=@', '=='],
]);
}
if(is_null($filter)) $filter = new Filter();
$filter_validator_rules = [
'first_name' => 'nullable|string',
'last_name' => 'nullable|string',
'email' => 'nullable|string',
'full_name' => 'nullable|string',
];
if(count($filter_validator_rules)) {
$filter->validate($filter_validator_rules);
}
$order = null;
if (Input::has('order'))
{
$order = OrderParser::parse(Input::get('order'), [
]);
}
$filter->addFilterCondition(FilterElement::makeEqual("group_id", $group_id));
$data = $this->user_repository->getAllByPage(new PagingInfo($page, $per_page), $filter, $order);
return $this->ok
(
$data->toArray
(
Input::get('expand', ''),
[],
[],
[],
SerializerRegistry::SerializerType_Private
)
);
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,103 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use Utils\Services\ILogService;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use Exception;
/**
* Class JsonController
* @package App\Http\Controllers
*/
abstract class JsonController extends Controller {
protected $log_service;
public function __construct(ILogService $log_service)
{
$this->log_service = $log_service;
}
protected function error500(Exception $ex){
$this->log_service->error($ex);
return Response::json(array( 'error' => 'server error'), 500);
}
protected function created($data='ok'){
$res = Response::json($data, 201);
//jsonp
if(Input::has('callback'))
$res->setCallback(Input::get('callback'));
return $res;
}
protected function updated($data = 'ok', $has_content = true)
{
$res = Response::json($data, $has_content ? 201 : 204);
//jsonp
if (Input::has('callback')) {
$res->setCallback(Input::get('callback'));
}
return $res;
}
protected function deleted($data='ok'){
$res = Response::json($data, 204);
//jsonp
if(Input::has('callback'))
$res->setCallback(Input::get('callback'));
return $res;
}
protected function ok($data = 'ok'){
$res = Response::json($data, 200);
//jsonp
if(Input::has('callback'))
$res->setCallback(Input::get('callback'));
return $res;
}
protected function error400($data = ['message' => 'Bad Request']){
return Response::json($data, 400);
}
protected function error404($data = array('message' => 'Entity Not Found')){
return Response::json($data, 404);
}
protected function error403($data = array('message' => 'Forbidden'))
{
return Response::json($data, 403);
}
/**
* {
"message": "Validation Failed",
"errors": [
{
"resource": "Issue",
"field": "title",
"code": "missing_field"
}
]
}
* @param $messages
* @return mixed
*/
protected function error412($messages){
return Response::json(array('error'=>'validation' , 'messages' => $messages), 412);
}
}

View File

@ -1,66 +0,0 @@
<?php namespace App\Http\Controllers\Api\OAuth2;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\Auth\IDisqusSSOService;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\IResourceServerContext;
use Utils\Services\ILogService;
/**
* Class OAuth2DisqusSSOApiController
* @package App\Http\Controllers\Api\OAuth2
*/
final class OAuth2DisqusSSOApiController extends OAuth2ProtectedController
{
/**
* @var IDisqusSSOService
*/
private $service;
public function __construct
(
IDisqusSSOService $service,
IResourceServerContext $resource_server_context,
ILogService $log_service
)
{
parent::__construct($resource_server_context, $log_service);
$this->service = $service;
}
/**
* @param string $forum_slug
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getUserProfile(string $forum_slug){
try{
$profile = $this->service->getUserProfile($forum_slug);
return $this->ok($profile->serialize());
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412([$ex->getMessage()]);
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(['message'=> $ex->getMessage()]);
}
catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,48 +0,0 @@
<?php namespace App\Http\Controllers\Api\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\IResourceServerContext;
use Utils\Services\ILogService;
use App\Http\Controllers\Api\JsonController;
/**
* Class OAuth2ProtectedController
* @package App\Http\Controllers\Api\OAuth2
*/
abstract class OAuth2ProtectedController extends JsonController
{
/**
* @var IResourceServerContext
*/
protected $resource_server_context;
/**
* @var
*/
protected $repository;
/**
* OAuth2ProtectedController constructor.
* @param IResourceServerContext $resource_server_context
* @param ILogService $log_service
*/
public function __construct
(
IResourceServerContext $resource_server_context,
ILogService $log_service
)
{
parent::__construct($log_service);
$this->resource_server_context = $resource_server_context;
}
}

View File

@ -1,65 +0,0 @@
<?php namespace App\Http\Controllers\Api\OAuth2;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\Auth\IRocketChatSSOService;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\IResourceServerContext;
use Utils\Services\ILogService;
/**
* Class OAuth2RocketChatSSOApiController
* @package App\Http\Controllers\Api\OAuth2
*/
class OAuth2RocketChatSSOApiController extends OAuth2ProtectedController
{
/**
* @var IRocketChatSSOService
*/
private $service;
public function __construct
(
IRocketChatSSOService $service,
IResourceServerContext $resource_server_context,
ILogService $log_service
)
{
parent::__construct($resource_server_context, $log_service);
$this->service = $service;
}
/**
* @param string $forum_slug
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getUserProfile(string $forum_slug){
try{
$profile = $this->service->getUserProfile($forum_slug);
return $this->ok($profile->serialize());
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412([$ex->getMessage()]);
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(['message'=> $ex->getMessage()]);
}
catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,66 +0,0 @@
<?php namespace App\Http\Controllers\Api\OAuth2;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\Auth\IStreamChatSSOService;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\IResourceServerContext;
use Utils\Services\ILogService;
/**
* Class OAuth2StreamChatSSOApiController
* @package App\Http\Controllers\Api\OAuth2
*/
class OAuth2StreamChatSSOApiController extends OAuth2ProtectedController
{
/**
* @var IStreamChatSSOService
*/
private $service;
public function __construct
(
IStreamChatSSOService $service,
IResourceServerContext $resource_server_context,
ILogService $log_service
)
{
parent::__construct($resource_server_context, $log_service);
$this->service = $service;
}
/**
* @param string $forum_slug
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getUserProfile(string $forum_slug){
try{
$profile = $this->service->getUserProfile($forum_slug);
return $this->ok($profile->serialize());
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412([$ex->getMessage()]);
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(['message'=> $ex->getMessage()]);
}
catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,284 +0,0 @@
<?php namespace App\Http\Controllers\Api\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\GetAllTrait;
use App\Http\Controllers\UserValidationRulesFactory;
use App\Http\Utils\HTMLCleaner;
use App\ModelSerializers\SerializerRegistry;
use Auth\Repositories\IUserRepository;
use Illuminate\Http\Request as LaravelRequest;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\Builders\IdTokenBuilder;
use OAuth2\IResourceServerContext;
use OAuth2\Repositories\IClientRepository;
use OAuth2\ResourceServer\IUserService;
use Utils\Http\HttpContentType;
use Utils\Services\ILogService;
use Exception;
use OpenId\Services\IUserService as IOpenIdUserService;
/**
* Class OAuth2UserApiController
* @package App\Http\Controllers\Api\OAuth2
*/
final class OAuth2UserApiController extends OAuth2ProtectedController
{
use GetAllTrait;
protected function getAllSerializerType(): string
{
return SerializerRegistry::SerializerType_Private;
}
/**
* @return array
*/
protected function getFilterRules(): array
{
return [
'first_name' => ['=@', '=='],
'last_name' => ['=@', '=='],
'email' => ['=@', '=='],
'primary_email' => ['=@', '=='],
];
}
public function getOrderRules(): array
{
return [];
}
/**
* @return array
*/
protected function getFilterValidatorRules(): array
{
return [
'first_name' => 'sometimes|required|string',
'last_name' => 'sometimes|required|string',
'email' => 'sometimes|required|string',
'primary_email' => 'sometimes|required|string',
];
}
/**
* @var IUserService
*/
private $user_service;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IdTokenBuilder
*/
private $id_token_builder;
/**
* @var IOpenIdUserService
*/
private $openid_user_service;
/**
* OAuth2UserApiController constructor.
* @param IUserRepository $repository
* @param IUserService $user_service
* @param IResourceServerContext $resource_server_context
* @param ILogService $log_service
* @param IOpenIdUserService $openid_user_service
* @param IClientRepository $client_repository
* @param IdTokenBuilder $id_token_builder
*/
public function __construct
(
IUserRepository $repository,
IUserService $user_service,
IResourceServerContext $resource_server_context,
ILogService $log_service,
IOpenIdUserService $openid_user_service,
IClientRepository $client_repository,
IdTokenBuilder $id_token_builder
)
{
parent::__construct($resource_server_context, $log_service);
$this->repository = $repository;
$this->user_service = $user_service;
$this->client_repository = $client_repository;
$this->id_token_builder = $id_token_builder;
$this->openid_user_service = $openid_user_service;
}
/**
* Gets User Basic Info
* @return mixed
*/
public function me()
{
try {
$data = $this->user_service->getCurrentUserInfo();
return $this->ok($data);
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
protected function curateUpdatePayload(array $payload): array
{
// remove possible fields that an user can not update
// from this endpoint
if(isset($payload['groups']))
unset($payload['groups']);
if(isset($payload['email_verified']))
unset($payload['email_verified']);
if(isset($payload['active']))
unset($payload['active']);
return HTMLCleaner::cleanData($payload, [
'bio', 'statement_of_interest'
]);
}
public function UpdateMe(){
try {
if(!Request::isJson()) return $this->error400();
if(!$this->resource_server_context->getCurrentUserId()){
return $this->error403();
}
$payload = Input::json()->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, UserValidationRulesFactory::build($payload, true));
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
$user = $this->openid_user_service->update($this->resource_server_context->getCurrentUserId(), $this->curateUpdatePayload($payload));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($user, SerializerRegistry::SerializerType_Private)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function UpdateMyPic(LaravelRequest $request){
try {
if (!$this->resource_server_context->getCurrentUserId()) {
return $this->error403();
}
$file = $request->hasFile('file') ? $request->file('file'):null;
if(is_null($file)){
throw new ValidationException('file is not present');
}
$user = $this->openid_user_service->updateProfilePhoto($this->resource_server_context->getCurrentUserId(), $file);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($user, SerializerRegistry::SerializerType_Private)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function userInfo()
{
try {
$claims = $this->user_service->getCurrentUserInfoClaims();
$client_id = $this->resource_server_context->getCurrentClientId();
$client = $this->client_repository->getClientById($client_id);
// The UserInfo Claims MUST be returned as the members of a JSON object unless a signed or encrypted response
// was requested during Client Registration.
$user_info_response_info = $client->getUserInfoResponseInfo();
$sig_alg = $user_info_response_info->getSigningAlgorithm();
$enc_alg = $user_info_response_info->getEncryptionKeyAlgorithm();
$enc = $user_info_response_info->getEncryptionContentAlgorithm();
if ($sig_alg || ($enc_alg && $enc)) {
$jwt = $this->id_token_builder->buildJWT($claims, $user_info_response_info, $client);
$http_response = Response::make($jwt->toCompactSerialization(), 200);
$http_response->header('Content-Type', HttpContentType::JWT);
$http_response->header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate');
$http_response->header('Pragma', 'no-cache');
return $http_response;
} else {
// return plain json
return $this->ok($claims->toArray());
}
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function get($id)
{
try {
$user = $this->repository->getById(intval($id));
if (is_null($user)) {
throw new EntityNotFoundException();
}
return $this->ok(SerializerRegistry::getInstance()->getSerializer($user, SerializerRegistry::SerializerType_Private)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412($ex1->getMessages());
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,97 +0,0 @@
<?php namespace App\Http\Controllers\Api\OAuth2;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\ModelSerializers\SerializerRegistry;
use App\Services\Auth\IUserService;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\IResourceServerContext;
use Utils\Services\ILogService;
/**
* Class OAuth2UserRegistrationRequestApiController
* @package App\Http\Controllers\Api\OAuth2
*/
final class OAuth2UserRegistrationRequestApiController extends OAuth2ProtectedController
{
/**
* @var IUserService
*/
private $user_service;
/**
* @param IUserService $user_service
* @param IResourceServerContext $resource_server_context
* @param ILogService $log_service
*/
public function __construct
(
IUserService $user_service,
IResourceServerContext $resource_server_context,
ILogService $log_service
)
{
parent::__construct($resource_server_context, $log_service);
$this->user_service = $user_service;
}
public function register(){
try {
if(!Request::isJson()) return $this->error400();
$payload = Input::json()->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'country' => 'sometimes|required|string|country_iso_alpha2_code',
]);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$registration_request = $this->user_service->createRegistrationRequest
(
$this->resource_server_context->getCurrentClientId(),
$payload
);
return $this->created(SerializerRegistry::getInstance()->getSerializer($registration_request)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
}
catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,55 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Repositories\IServerPrivateKeyRepository;
use OAuth2\Services\IServerPrivateKeyService;
use Utils\Services\ILogService;
/**
* Class ServerPrivateKeyApiController
* @package App\Http\Controllers\Api
*/
final class ServerPrivateKeyApiController extends AsymmetricKeyApiController
{
/**
* @param IServerPrivateKeyRepository $repository
* @param IServerPrivateKeyService $service
* @param ILogService $log_service
*/
public function __construct
(
IServerPrivateKeyRepository $repository,
IServerPrivateKeyService $service,
ILogService $log_service
)
{
parent::__construct($repository, $service, $log_service);
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return [
'kid' => 'required|text|min:5|max:255',
'active' => 'required|boolean',
'valid_from' => 'date_format:m/d/Y',
'valid_to' => 'date_format:m/d/Y|after:valid_from',
'pem_content' => 'sometimes|required|private_key_pem:password|private_key_pem_length:password',
'usage' => 'required|public_key_usage',
'type' => 'required|public_key_type',
'alg' => 'required|key_alg:usage',
'password' => 'min:5|max:255|private_key_password:pem_content',
];
}
}

View File

@ -1,270 +0,0 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\APICRUDController;
use App\Http\Controllers\UserValidationRulesFactory;
use App\Http\Utils\HTMLCleaner;
use App\ModelSerializers\SerializerRegistry;
use Auth\Repositories\IUserRepository;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use models\exceptions\ValidationException;
use OAuth2\Services\ITokenService;
use OpenId\Services\IUserService;
use models\exceptions\EntityNotFoundException;
use Utils\Services\ILogService;
use Illuminate\Http\Request as LaravelRequest;
/**
* Class UserApiController
* @package App\Http\Controllers\Api
*/
final class UserApiController extends APICRUDController
{
/**
* @var ITokenService
*/
private $token_service;
/**
* UserApiController constructor.
* @param IUserRepository $user_repository
* @param ILogService $log_service
* @param IUserService $user_service
* @param ITokenService $token_service
*/
public function __construct
(
IUserRepository $user_repository,
ILogService $log_service,
IUserService $user_service,
ITokenService $token_service
)
{
parent::__construct($user_repository, $user_service, $log_service);
$this->token_service = $token_service;
}
/**
* @return array
*/
protected function getFilterRules(): array
{
return [
'first_name' => ['=@', '=='],
'last_name' => ['=@', '=='],
'full_name' => ['=@', '=='],
'email' => ['=@', '=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules(): array
{
return [
'first_name' => 'nullable|string',
'last_name' => 'nullable|string',
'full_name' => 'nullable|string',
'email' => 'nullable|string',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'first_name',
'last_name',
'email',
'identifier',
'last_login_date',
'spam_type'
];
}
/**
* @param $id
* @return mixed
*/
public function unlock($id)
{
try {
$entity = $this->service->unlockUser($id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function lock($id)
{
try {
$entity = $this->service->lockUser($id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
protected function getAllSerializerType(): string
{
return SerializerRegistry::SerializerType_Private;
}
/**
* @param $id
* @param $value
* @return mixed
*/
public function revokeMyToken($value)
{
try {
$hint = Input::get('hint', 'none');
switch ($hint) {
case 'access-token':
{
$this->token_service->revokeAccessToken($value, true);
}
break;
case 'refresh-token':
$this->token_service->revokeRefreshToken($value, true);
break;
default:
throw new Exception(sprintf("hint %s not allowed", $hint));
break;
}
return $this->deleted();
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return array
*/
protected function getUpdatePayloadValidationRules(): array
{
return UserValidationRulesFactory::build([], true, true);
}
protected function curateUpdatePayload(array $payload): array
{
if(in_array("bio", $payload)){
$payload["bio"] = strip_tags($payload["bio"]);
}
if(in_array("statement_of_interest", $payload)){
$payload["statement_of_interest"] = strip_tags($payload["statement_of_interest"]);
}
return $payload;
}
protected function curateCreatePayload(array $payload): array
{
if(in_array("bio", $payload)){
$payload["bio"] = strip_tags($payload["bio"]);
}
if(in_array("statement_of_interest", $payload)){
$payload["statement_of_interest"] = strip_tags($payload["statement_of_interest"]);
}
return $payload;
}
/**
* @return array
*/
protected function getCreatePayloadValidationRules(): array
{
return UserValidationRulesFactory::build([], false, true);
}
/**
* @param LaravelRequest $request
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function updateMe(LaravelRequest $request)
{
if (!Auth::check())
return $this->error403();
$myId = Auth::user()->getId();
return $this->update($myId);
}
/**
* @return array
*/
protected function getUpdatePayload():array{
$payload = request()->all();
if(isset($payload['user'])){
$payload = json_decode($payload['user'],true);
if(is_null($payload)){
Log::warning(sprintf("UserApiController::getUpdatePayload can not decode %s ", $payload['user']));
return [];
}
}
return $payload;
}
/**
* @param $id
* @param $payload
* @return \models\utils\IEntity
*/
protected function onUpdate($id, $payload){
$user = parent::onUpdate($id, $payload);
$file = request()->file('pic');
if (!is_null($file)) {
$user = $this->service->updateProfilePhoto($id, $file);
}
return $user;
}
protected function serializerType(): string
{
return SerializerRegistry::SerializerType_Private;
}
}

View File

@ -1,114 +0,0 @@
<?php namespace App\Http\Controllers\Auth;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use App\Services\Auth\IUserService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request as LaravelRequest;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
/**
* Class EmailVerificationController
* @package App\Http\Controllers\Auth
*/
final class EmailVerificationController extends Controller
{
/**
* @var IUserService
*/
private $user_service;
/**
* EmailVerificationController constructor.
* @param IUserService $user_service
*/
public function __construct(IUserService $user_service)
{
$this->user_service = $user_service;
}
public function showVerificationForm()
{
return view('auth.email_verification');
}
/**
* @param string $token
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function verify($token)
{
try {
$user = $this->user_service->verifyEmail($token);
return view('auth.email_verification_success', ['user' => $user]);
}
catch (EntityNotFoundException $ex){
Log::warning($ex);
}
catch (ValidationException $ex){
Log::warning($ex);
}
catch (\Exception $ex){
Log::error($ex);
}
return view('auth.email_verification_error');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255',
'g-recaptcha-response' => 'required|recaptcha',
]);
}
public function resend(LaravelRequest $request)
{
try {
$payload = $request->all();
$validator = $this->validator($payload);
if (!$validator->passes()) {
return Redirect::action('Auth\EmailVerificationController@showVerificationForm')->withErrors($validator);
}
$user = $this->user_service->resendVerificationEmail($payload);
return view("auth.email_verification_resend_success", ['user' => $user]);
}
catch (EntityNotFoundException $ex){
Log::warning($ex);
}
catch (ValidationException $ex){
Log::warning($ex);
foreach ($ex->getMessages() as $message){
$validator->getMessageBag()->add('validation', $message);
}
return Redirect::action('Auth\EmailVerificationController@showVerificationForm')->withErrors($validator);
}
catch(\Exception $ex){
Log::error($ex);
}
return view("auth.email_verification_error");
}
}

View File

@ -1,170 +0,0 @@
<?php namespace App\Http\Controllers\Auth;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use App\Services\Auth\IUserService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request as LaravelRequest;
use models\exceptions\ValidationException;
use OAuth2\Repositories\IClientRepository;
/**
* Class ForgotPasswordController
* @package App\Http\Controllers\Auth
*/
final class ForgotPasswordController extends Controller
{
/**
* @var IUserService
*/
private $user_service;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* ForgotPasswordController constructor.
* @param IClientRepository $client_repository
* @param IUserService $user_service
*/
public function __construct
(
IClientRepository $client_repository,
IUserService $user_service
)
{
$this->middleware('guest');
$this->user_service = $user_service;
$this->client_repository = $client_repository;
}
/**
* @param LaravelRequest $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showLinkRequestForm(LaravelRequest $request)
{
try {
$params = [
"redirect_uri" => '',
"client_id" => '',
];
// check if we have explicit params at query string
if ($request->has("redirect_uri") && $request->has("client_id")) {
$redirect_uri = $request->get("redirect_uri");
$client_id = $request->get("client_id");
$client = $this->client_repository->getClientById($client_id);
if (is_null($client))
throw new ValidationException("client does not exists");
if (!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$params['redirect_uri'] = $redirect_uri;
$params['client_id'] = $client_id;
}
return view('auth.passwords.email', $params);
} catch (\Exception $ex) {
Log::warning($ex);
}
return view("auth.passwords.email_error");
}
/**
* Send a reset link to the given user.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function sendResetLinkEmail(LaravelRequest $request)
{
try {
$payload = $request->all();
$validator = $this->validator($payload);
if (!$validator->passes()) {
return back()
->withInput($request->only('email', 'client_id', 'redirect_uri'))
->withErrors($validator);
}
$this->user_service->requestPasswordReset($payload);
$params = [
'client_id' => '',
'redirect_uri' => '',
];
// check redirect uri with associated client
if($request->has("redirect_uri") && $request->has("client_id")){
$redirect_uri = $request->get("redirect_uri");
$client_id = $request->get("client_id");
$client = $this->client_repository->getClientById($client_id);
if(is_null($client))
throw new ValidationException("client does not exists");
if(!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$params['client_id'] = $client_id;
$params['redirect_uri'] = $redirect_uri;
}
$params['status'] = 'Reset link sent';
return back()->with($params);
} catch (ValidationException $ex) {
Log::warning($ex);
foreach ($ex->getMessages() as $message) {
$validator->getMessageBag()->add('validation', $message);
}
return back()
->withInput($request->only(['email', 'client_id', 'redirect_uri']))
->withErrors($validator);
} catch (\Exception $ex) {
Log::warning($ex);
}
return view("auth.passwords.email_error");
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255',
]);
}
/**
* Get the response for a successful password reset link.
*
* @param string $response
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetLinkResponse($response)
{
}
}

View File

@ -1,216 +0,0 @@
<?php namespace App\Http\Controllers\Auth;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use App\libs\Auth\Repositories\IUserRegistrationRequestRepository;
use App\Services\Auth\IUserService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request as LaravelRequest;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use OAuth2\Repositories\IClientRepository;
/**
* Class PasswordSetController
* @package App\Http\Controllers\Auth
*/
final class PasswordSetController extends Controller
{
/**
* @var IUserService
*/
private $user_service;
/**
* @var IUserRegistrationRequestRepository
*/
private $user_registration_request_repository;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* PasswordSetController constructor.
* @param IUserRegistrationRequestRepository $user_registration_request_repository
* @param IClientRepository $client_repository
* @param IUserService $user_service
*/
public function __construct
(
IUserRegistrationRequestRepository $user_registration_request_repository,
IClientRepository $client_repository,
IUserService $user_service
)
{
$this->middleware('guest');
$this->user_service = $user_service;
$this->user_registration_request_repository = $user_registration_request_repository;
$this->client_repository = $client_repository;
}
/**
* @param $token
* @param LaravelRequest $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showPasswordSetForm($token, LaravelRequest $request)
{
try {
$user_registration_request = $this->user_registration_request_repository->getByHash($token);
if(is_null($user_registration_request))
throw new EntityNotFoundException("request not found");
if($user_registration_request->isRedeem()) {
// check redirect uri
if($request->has("redirect_uri") && $request->has("client_id")){
$redirect_uri = $request->get("redirect_uri");
$client_id = $request->get("client_id");
$client = $this->client_repository->getClientById($client_id);
if(is_null($client))
throw new ValidationException("client does not exists");
if(!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$params['client_id'] = $client_id;
$params['redirect_uri'] = $redirect_uri;
$params['email'] = $user_registration_request->getEmail();
return view("auth.passwords.set_success", $params);
}
throw new ValidationException("request already redeem!");
}
$params = [
"email" => $user_registration_request->getEmail(),
"token" => $token,
"redirect_uri" => '',
"client_id" => '',
];
if($request->has("redirect_uri") && $request->has("client_id")){
$redirect_uri = $request->get("redirect_uri");
$client_id = $request->get("client_id");
$client = $this->client_repository->getClientById($client_id);
if(is_null($client))
throw new ValidationException("client does not exists");
if(!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$params['redirect_uri'] = $redirect_uri;
$params['client_id'] = $client_id;
}
return view('auth.passwords.set', $params);
}
catch(EntityNotFoundException $ex){
Log::warning($ex);
}
catch(ValidationException $ex){
Log::warning($ex);
}
catch (\Exception $ex){
Log::error($ex);
}
return view('auth.passwords.set_error');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'token' => 'required',
'password' => 'required|string|confirmed|password_policy',
'g-recaptcha-response' => 'required|recaptcha',
]);
}
/**
* @param LaravelRequest $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
*/
public function setPassword(LaravelRequest $request)
{
try {
$payload = $request->all();
$validator = $this->validator($payload);
if (!$validator->passes()) {
return back()
->withInput($request->only(['token','client_id', 'redirect_uri', 'email']))
->withErrors($validator);
}
$user_registration_request = $this->user_service->setPassword($payload['token'], $payload['password']);
$params = [
'client_id' => '',
'redirect_uri' => '',
'email' => '',
];
// check redirect uri with associated client
if($request->has("redirect_uri") && $request->has("client_id")){
$redirect_uri = $request->get("redirect_uri");
$client_id = $request->get("client_id");
$client = $this->client_repository->getClientById($client_id);
if(is_null($client))
throw new ValidationException("client does not exists");
if(!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$params['client_id'] = $client_id;
$params['redirect_uri'] = $redirect_uri;
$params['email'] = $user_registration_request->getEmail();
}
Auth::login($user_registration_request->getOwner(), true);
return view("auth.passwords.set_success", $params);
}
catch (EntityNotFoundException $ex){
Log::warning($ex);
}
catch (ValidationException $ex){
Log::warning($ex);
foreach ($ex->getMessages() as $message){
$validator->getMessageBag()->add('validation', $message);
}
return back()
->withInput($request->only(['token','client_id', 'redirect_uri', 'email']))
->withErrors($validator);
}
catch(\Exception $ex){
Log::warning($ex);
}
return view("auth.passwords.reset_error");
}
}

View File

@ -1,263 +0,0 @@
<?php namespace App\Http\Controllers\Auth;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use App\Http\Utils\CountryList;
use App\Services\Auth\IUserService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request as LaravelRequest;
use models\exceptions\ValidationException;
use OAuth2\Factories\OAuth2AuthorizationRequestFactory;
use OAuth2\OAuth2Message;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Services\IMementoOAuth2SerializerService;
use Sokil\IsoCodes\IsoCodesFactory;
use Exception;
/**
* Class RegisterController
* @package App\Http\Controllers\Auth
*/
final class RegisterController extends Controller
{
/**
* @var IUserService
*/
private $user_service;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IMementoOAuth2SerializerService
*/
private $memento_service;
public function __construct
(
IClientRepository $client_repository,
IUserService $user_service,
IMementoOAuth2SerializerService $memento_service
)
{
$this->middleware('guest');
$this->user_service = $user_service;
$this->client_repository = $client_repository;
$this->memento_service = $memento_service;
}
/**
* @param LaravelRequest $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @throws ValidationException
*/
public function showRegistrationForm(LaravelRequest $request)
{
try {
$params = [
"redirect_uri" => '',
"email" => '',
"first_name" => '',
"last_name" => '',
"client_id" => '',
'countries' => CountryList::getCountries()
];
// check if we have a former oauth2 request
if ($this->memento_service->exists()) {
Log::debug("RegisterController::showRegistrationForm exist a oauth auth request on session");
$oauth_auth_request = OAuth2AuthorizationRequestFactory::getInstance()->build
(
OAuth2Message::buildFromMemento($this->memento_service->load())
);
if ($oauth_auth_request->isValid()) {
$redirect_uri = $oauth_auth_request->getRedirectUri();
$client_id = $oauth_auth_request->getClientId();
Log::debug(sprintf( "RegisterController::showRegistrationForm exist a oauth auth request is valid for client id %s", $client_id));
$client = $this->client_repository->getClientById($client_id);
if (is_null($client))
throw new ValidationException("client does not exists");
if (!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$this->memento_service->serialize($oauth_auth_request->getMessage()->createMemento());
}
}
// check if we have explicit params at query string
if ($request->has("redirect_uri") && $request->has("client_id")) {
$redirect_uri = $request->get("redirect_uri");
$client_id = $request->get("client_id");
$client = $this->client_repository->getClientById($client_id);
if (is_null($client))
throw new ValidationException("client does not exists");
if (!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$params['redirect_uri'] = $redirect_uri;
$params['client_id'] = $client_id;
}
if($request->has('email')){
$params['email'] = $request->get("email");
}
if($request->has('first_name')){
$params['first_name'] = $request->get("first_name");
}
if($request->has('last_name')){
$params['last_name'] = $request->get("last_name");
}
return view('auth.register', $params);
}
catch(\Exception $ex){
Log::warning($ex);
}
return view("auth.register_error");
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$rules = [
'first_name' => 'required|string|max:100',
'last_name' => 'required|string|max:100',
'country_iso_code' => 'required|string|country_iso_alpha2_code',
'email' => 'required|string|email|max:255',
'password' => 'required|string|confirmed|password_policy',
'g-recaptcha-response' => 'required|recaptcha',
];
if(!empty(Config::get("app.code_of_conduct_link", null))){
$rules['agree_code_of_conduct'] = 'required|string|in:on';
}
return Validator::make($data, $rules);
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function register(LaravelRequest $request)
{
$validator = null;
try {
$payload = $request->all();
$validator = $this->validator($payload);
if (!$validator->passes()) {
return back()
->withInput($request->only(['first_name', 'last_name', 'country_iso_code','email','client_id', 'redirect_uri']))
->withErrors($validator);
}
$user = $this->user_service->registerUser($payload);
$params = [
'client_id' => '',
'redirect_uri' => '',
];
// check if we have a former oauth2 request
if ($this->memento_service->exists()) {
Log::debug("RegisterController::register exist a oauth auth request on session");
$oauth_auth_request = OAuth2AuthorizationRequestFactory::getInstance()->build
(
OAuth2Message::buildFromMemento($this->memento_service->load())
);
if ($oauth_auth_request->isValid()) {
$redirect_uri = $oauth_auth_request->getRedirectUri();
$client_id = $oauth_auth_request->getClientId();
Log::debug(sprintf( "RegisterController::register exist a oauth auth request is valid for client id %s", $client_id));
$client = $this->client_repository->getClientById($client_id);
if (is_null($client))
throw new ValidationException("client does not exists");
if (!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$this->memento_service->serialize($oauth_auth_request->getMessage()->createMemento());
$params['redirect_uri'] = action('OAuth2\OAuth2ProviderController@auth');
Auth::login($user, false);
}
}
// check redirect uri with associated client
if($request->has("redirect_uri") && $request->has("client_id")){
$redirect_uri = $request->get("redirect_uri");
$client_id = $request->get("client_id");
$client = $this->client_repository->getClientById($client_id);
if(is_null($client))
throw new ValidationException("client does not exists");
if(!$client->isUriAllowed($redirect_uri))
throw new ValidationException(sprintf("redirect_uri %s is not allowed on associated client", $redirect_uri));
$params['client_id'] = $client_id;
$params['redirect_uri'] = $redirect_uri;
Auth::login($user, false);
}
return view("auth.register_success", $params);
}
catch (ValidationException $ex){
Log::warning($ex);
if(!is_null($validator)) {
$validator->getMessageBag()->add('validation', sprintf
(
"It looks like a user with this email address already exists." .
"You can either <a href='%s'>sign in</a> or <a href='%s'>reset your password</a> if you've forgotten it.",
URL::action("UserController@getLogin"),
URL::action("Auth\ForgotPasswordController@showLinkRequestForm")
));
}
return back()
->withInput($request->only(['first_name', 'last_name', 'country_iso_code','email']))
->withErrors($validator);
}
catch(Exception $ex){
Log::warning($ex);
}
return view("auth.register_error");
}
}

View File

@ -1,148 +0,0 @@
<?php namespace App\Http\Controllers\Auth;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use App\libs\Auth\Repositories\IUserPasswordResetRequestRepository;
use App\Services\Auth\IUserService;
use Auth\Repositories\IUserRepository;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request as LaravelRequest;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
/**
* Class ResetPasswordController
* @package App\Http\Controllers\Auth
*/
final class ResetPasswordController extends Controller
{
/**
* @var IUserService
*/
private $user_service;
/**
* @var IUserPasswordResetRequestRepository
*/
private $user_password_reset_request_repository;
/**
* ResetPasswordController constructor.
* @param IUserPasswordResetRequestRepository $user_password_reset_request_repository
* @param IUserService $user_service
*/
public function __construct
(
IUserPasswordResetRequestRepository $user_password_reset_request_repository,
IUserService $user_service
)
{
$this->middleware('guest');
$this->user_service = $user_service;
$this->user_password_reset_request_repository = $user_password_reset_request_repository;
}
/**
* @param $token
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showResetForm($token)
{
try {
$request = $this->user_password_reset_request_repository->getByToken($token);
if(is_null($request))
throw new EntityNotFoundException(sprintf("Request not found for token %s.", $token));
if(!$request->isValid())
throw new ValidationException("Request is void.");
if($request->isRedeem()){
throw new ValidationException("Request is already redeem.");
}
return view('auth.passwords.reset')->with(
[
'token' => $token,
'email' => $request->getOwner()->getEmail()
]);
}
catch (EntityNotFoundException $ex){
Log::warning($ex);
}
catch (ValidationException $ex){
Log::warning($ex);
}
catch(\Exception $ex){
Log::error($ex);
}
return view("auth.passwords.reset_error");
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'token' => 'required',
'password' => 'required|string|confirmed|password_policy',
'g-recaptcha-response' => 'required|recaptcha',
]);
}
/**
* Reset the given user's password.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function reset(LaravelRequest $request)
{
try {
$payload = $request->all();
$validator = $this->validator($payload);
if (!$validator->passes()) {
return back()
->withInput($request->only(['token', 'email']))
->withErrors($validator);
}
$this->user_service->resetPassword($payload['token'], $payload['password']);
return view("auth.passwords.reset_success");
}
catch (ValidationException $ex){
Log::warning($ex);
foreach ($ex->getMessages() as $message){
$validator->getMessageBag()->add('validation', $message);
}
return back()
->withInput($request->only(['token', 'email']))
->withErrors($validator);
}
catch(\Exception $ex){
Log::warning($ex);
}
return view("auth.passwords.reset_error");
}
}

View File

@ -1,25 +0,0 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
/**
* Class Controller
* @package App\Http\Controllers
*/
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

View File

@ -1,111 +0,0 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class UserValidationRulesFactory
* @package App\Http\Controllers
*/
final class UserValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @param bool $is_admin
* @return array
*/
public static function build(array $data, $update = false, $is_admin = false){
if($update){
$rules = [
'first_name' => 'sometimes|string',
'last_name' => 'sometimes|string',
'email' => 'sometimes|email',
'identifier' => 'sometimes|string',
'bio' => 'nullable|string',
'address1' => 'nullable|string',
'address2' => 'nullable|string',
'city' => 'nullable|string',
'state' => 'nullable|string',
'post_code' => 'nullable|string',
'country_iso_code' => 'nullable|country_iso_alpha2_code',
'second_email' => 'nullable|email',
'third_email' => 'nullable|email',
'gender' => 'nullable|string',
'gender_specify' => 'nullable|string',
'statement_of_interest' => 'nullable|string',
'irc' => 'nullable|string',
'linked_in_profile' => 'nullable|string',
'github_user' => 'nullable|string',
'wechat_user' => 'nullable|string',
'twitter_name' => 'nullable|string',
'language' => 'nullable|string',
'birthday' => 'nullable|date_format:U',
'password' => 'sometimes|string|confirmed|password_policy',
'phone_number' => 'nullable|string',
'company' => 'nullable|string',
'job_title' => 'nullable|string',
// admin fields
'email_verified' => 'nullable|boolean',
'active' => 'nullable|boolean',
'groups' => 'sometimes|int_array',
'public_profile_show_photo' => 'sometimes|boolean',
'public_profile_show_fullname' => 'sometimes|boolean',
'public_profile_show_email' => 'sometimes|boolean',
];
if(!$is_admin){
$rules['current_password'] = 'required_with:password';
}
return $rules;
}
return [
'first_name' => 'required|string',
'last_name' => 'required|string',
'email' => 'required|email',
'identifier' => 'sometimes|string',
'bio' => 'nullable|string',
'address1' => 'nullable|string',
'address2' => 'nullable|string',
'city' => 'nullable|string',
'state' => 'nullable|string',
'post_code' => 'nullable|string',
'country_iso_code' => 'nullable|country_iso_alpha2_code',
'second_email' => 'nullable|email',
'third_email' => 'nullable|email',
'gender' => 'nullable|string',
'statement_of_interest' => 'nullable|string',
'irc' => 'nullable|string',
'linked_in_profile' => 'nullable|string',
'github_user' => 'nullable|string',
'wechat_user' => 'nullable|string',
'twitter_name' => 'nullable|string',
'language' => 'nullable|string',
'birthday' => 'nullable|date_format:U',
'password' => 'sometimes|string|confirmed|password_policy',
'phone_number' => 'nullable|string',
'company' => 'nullable|string',
'job_title' => 'nullable|string',
// admin fields
'email_verified' => 'nullable|boolean',
'active' => 'nullable|boolean',
'groups' => 'sometimes|int_array',
'public_profile_show_photo' => 'sometimes|boolean',
'public_profile_show_fullname' => 'sometimes|boolean',
'public_profile_show_email' => 'sometimes|boolean',
];
}
}

View File

@ -1,47 +0,0 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Redirect;
use App\Http\Controllers\OpenId\OpenIdController;
use App\Http\Controllers\OpenId\DiscoveryController;
/**
* Class HomeController
* @package App\Http\Controllers
*/
class HomeController extends OpenIdController
{
private $discovery;
public function __construct(DiscoveryController $discovery)
{
$this->discovery = $discovery;
}
public function index()
{
if ($this->isDiscoveryRequest())
return $this->discovery->idp();
if (Auth::guest()) {
Session::flush();
Session::regenerate();
return View::make("home");
}
else
return Redirect::action("UserController@getProfile");
}
}

View File

@ -1,294 +0,0 @@
<?php namespace App\Http\Controllers\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;
use OAuth2\Exceptions\OAuth2BaseException;
use OAuth2\Factories\OAuth2AuthorizationRequestFactory;
use OAuth2\IOAuth2Protocol;
use OAuth2\OAuth2Message;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Requests\OAuth2AccessTokenValidationRequest;
use OAuth2\Requests\OAuth2LogoutRequest;
use OAuth2\Requests\OAuth2TokenRequest;
use OAuth2\Requests\OAuth2TokenRevocationRequest;
use OAuth2\Responses\OAuth2Response;
use OAuth2\Strategies\OAuth2ResponseStrategyFactoryMethod;
use Utils\Http\HttpContentType;
use Utils\Services\IAuthService;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Exception;
/**
* Class OAuth2ProviderController
*/
final class OAuth2ProviderController extends Controller
{
/**
* @var IOAuth2Protocol
*/
private $oauth2_protocol;
/**
* @var IAuthService
*/
private $auth_service;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @param IOAuth2Protocol $oauth2_protocol
* @param IClientRepository $client_repository
* @param IAuthService $auth_service
*/
public function __construct
(
IOAuth2Protocol $oauth2_protocol,
IClientRepository $client_repository,
IAuthService $auth_service
)
{
$this->oauth2_protocol = $oauth2_protocol;
$this->auth_service = $auth_service;
$this->client_repository = $client_repository;
}
/**
* Authorize HTTP Endpoint
* The authorization server MUST support the use of the HTTP "GET"
* method [RFC2616] for the authorization endpoint and MAY support the
* use of the "POST" method as well.
* @return mixed
*/
public function auth()
{
try
{
$response = $this->oauth2_protocol->authorize
(
OAuth2AuthorizationRequestFactory::getInstance()->build
(
new OAuth2Message
(
Input::all()
)
)
);
if ($response instanceof OAuth2Response) {
$strategy = OAuth2ResponseStrategyFactoryMethod::buildStrategy
(
$this->oauth2_protocol->getLastRequest(),
$response
);
return $strategy->handle($response);
}
return $response;
}
catch(OAuth2BaseException $ex1)
{
return Response::view
(
'errors.400',
array
(
'error' => $ex1->getError(),
'error_description' => $ex1->getMessage()
),
400
);
}
catch(Exception $ex)
{
Log::error($ex);
return Response::view
(
'errors.400',
array
(
'error' => "Bad Request",
'error_description' => "Generic Error"
),
400
);
}
}
/**
* Token HTTP Endpoint
* @return mixed
*/
public function token()
{
$response = $this->oauth2_protocol->token
(
new OAuth2TokenRequest
(
new OAuth2Message
(
Input::all()
)
)
);
if ($response instanceof OAuth2Response)
{
$strategy = OAuth2ResponseStrategyFactoryMethod::buildStrategy
(
$this->oauth2_protocol->getLastRequest(),
$response
);
return $strategy->handle($response);
}
return $response;
}
/**
* Revoke Token HTTP Endpoint
* @return mixed
*/
public function revoke()
{
$response = $this->oauth2_protocol->revoke
(
new OAuth2TokenRevocationRequest
(
new OAuth2Message
(
Input::all()
)
)
);
if ($response instanceof OAuth2Response)
{
$strategy = OAuth2ResponseStrategyFactoryMethod::buildStrategy
(
$this->oauth2_protocol->getLastRequest(),
$response
);
return $strategy->handle($response);
}
return $response;
}
/**
* @see http://tools.ietf.org/html/draft-richer-oauth-introspection-04
* Introspection Token HTTP Endpoint
* @return mixed
*/
public function introspection()
{
$response = $this->oauth2_protocol->introspection
(
new OAuth2AccessTokenValidationRequest
(
new OAuth2Message
(
Input::all()
)
)
);
if ($response instanceof OAuth2Response)
{
$strategy = OAuth2ResponseStrategyFactoryMethod::buildStrategy
(
$this->oauth2_protocol->getLastRequest(),
$response
);
return $strategy->handle($response);
}
return $response;
}
/**
* OP's JSON Web Key Set [JWK] document.
* @return string
*/
public function certs()
{
$doc = $this->oauth2_protocol->getJWKSDocument();
$response = Response::make($doc, 200);
$response->header('Content-Type', HttpContentType::Json);
return $response;
}
public function discovery()
{
$doc = $this->oauth2_protocol->getDiscoveryDocument();
$response = Response::make($doc, 200);
$response->header('Content-Type', HttpContentType::Json);
return $response;
}
/**
* @see http://openid.net/specs/openid-connect-session-1_0.html#OPiframe
*/
public function checkSessionIFrame()
{
$data = [];
return View::make("oauth2.session.check-session", $data);
}
/**
* @see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
*/
public function endSession()
{
$request = new OAuth2LogoutRequest
(
new OAuth2Message
(
Input::all()
)
);
if(!$request->isValid())
{
Log::error('invalid OAuth2LogoutRequest!');
return Response::view('errors.400', [
'error' => 'Invalid logout request.',
'error_description' => $request->getLastValidationError()
], 400);
}
$response = $this->oauth2_protocol->endSession($request);
if (!is_null($response) && $response instanceof OAuth2Response) {
$strategy = OAuth2ResponseStrategyFactoryMethod::buildStrategy($request, $response);
return $strategy->handle($response);
}
return View::make('oauth2.session.session-ended');
}
}

View File

@ -1,88 +0,0 @@
<?php namespace App\Http\Controllers\OpenId;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OpenId\IOpenIdProtocol;
use OpenId\Services\IServerConfigurationService;
use Utils\Services\IAuthService;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Response;
/**
* Class DiscoveryController
* @package App\Http\Controllers\OpenId
*/
class DiscoveryController extends OpenIdController
{
/**
* @var IOpenIdProtocol
*/
private $openid_protocol;
/**
* @var IAuthService
*/
private $auth_service;
/**
* @var IServerConfigurationService
*/
private $server_config_service;
/**
* DiscoveryController constructor.
* @param IOpenIdProtocol $openid_protocol
* @param IAuthService $auth_service
* @param IServerConfigurationService $server_config_service
*/
public function __construct
(
IOpenIdProtocol $openid_protocol,
IAuthService $auth_service,
IServerConfigurationService $server_config_service
)
{
$this->openid_protocol = $openid_protocol;
$this->auth_service = $auth_service;
$this->server_config_service = $server_config_service;
}
/**
* XRDS discovery(eXtensible Resource Descriptor Sequence)
* @return xrds document on response
*/
public function idp()
{
$response = Response::make($this->openid_protocol->getXRDSDiscovery(IOpenIdProtocol::OpenIdXRDSModeIdp), 200);
$this->setDiscoveryResponseType($response);
return $response;
}
/**
* If the Claimed Identifier was not previously discovered by the Relying Party
* (the "openid.identity" in the request was "http://specs.openid.net/auth/2.0/identifier_select"
* or a different Identifier, or if the OP is sending an unsolicited positive assertion),
* the Relying Party MUST perform discovery on the Claimed Identifier in
* the response to make sure that the OP is authorized to make assertions about the Claimed Identifier.
* @param $identifier
* @return mixed
*/
public function user($identifier)
{
$user = $this->auth_service->getUserByOpenId($identifier);
if (is_null($user))
return View::make("errors.404");
$local_identifier = $this->server_config_service->getUserIdentityEndpointURL($identifier);
$response = Response::make($this->openid_protocol->getXRDSDiscovery(IOpenIdProtocol::OpenIdXRDSModeUser, $local_identifier), 200);
$this->setDiscoveryResponseType($response);
return $response;
}
}

View File

@ -1,39 +0,0 @@
<?php namespace App\Http\Controllers\OpenId;
/**
* Copyright 2015 Openstack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Request;
use OpenId\Xrds\XRDSDocumentBuilder;
use App\Http\Controllers\Controller;
/**
* Class OpenIdController
* @package App\Http\Controllers\OpenId
*/
abstract class OpenIdController extends Controller {
/**
* @return bool
*/
protected function isDiscoveryRequest(){
//This field contains a semicolon-separated list of representation schemes
//which will be accepted in the response to this request.
$accept = Request::header('Accept');
return strstr($accept, XRDSDocumentBuilder::ContentType) !== false;
}
/**
* @param $response
*/
protected function setDiscoveryResponseType($response){
$response->header('Content-Type', implode('; ', array(XRDSDocumentBuilder::ContentType, XRDSDocumentBuilder::Charset)));
}
}

View File

@ -1,105 +0,0 @@
<?php namespace App\Http\Controllers\OpenId;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use OpenId\Exceptions\InvalidOpenIdMessageException;
use OpenId\Exceptions\OpenIdBaseException;
use OpenId\Helpers\OpenIdErrorMessages;
use OpenId\IOpenIdProtocol;
use OpenId\OpenIdMessage;
use OpenId\Responses\OpenIdResponse;
use OpenId\Services\IMementoOpenIdSerializerService;
use OpenId\Strategies\OpenIdResponseStrategyFactoryMethod;
/**
* Class OpenIdProviderController
* @package App\Http\Controllers\OpenId
*/
class OpenIdProviderController extends Controller
{
/**
* @var IOpenIdProtocol
*/
private $openid_protocol;
/**
* @var IMementoOpenIdSerializerService
*/
private $memento_service;
/**
* @param IOpenIdProtocol $openid_protocol
* @param IMementoOpenIdSerializerService $memento_service
*/
public function __construct(IOpenIdProtocol $openid_protocol, IMementoOpenIdSerializerService $memento_service)
{
$this->openid_protocol = $openid_protocol;
$this->memento_service = $memento_service;
}
/**
* @return OpenIdResponse
* @throws Exception
* @throws InvalidOpenIdMessageException
*/
public function endpoint()
{
try {
$msg = new OpenIdMessage(Input::all());
if (!$msg->isValid() && $this->memento_service->exists()) {
$msg = OpenIdMessage::buildFromMemento($this->memento_service->load());
}
if (!$msg->isValid())
throw new InvalidOpenIdMessageException(OpenIdErrorMessages::InvalidOpenIdMessage);
//get response and manage it taking in consideration its type (direct or indirect)
$response = $this->openid_protocol->handleOpenIdMessage($msg);
if ($response instanceof OpenIdResponse) {
$strategy = OpenIdResponseStrategyFactoryMethod::buildStrategy($response);
return $strategy->handle($response);
}
return $response;
}
catch(OpenIdBaseException $ex1){
Log::warning($ex1);
return Response::view
(
'errors.400',
array
(
'error' => "Bad Request",
'error_description' => $ex1->getMessage()
),
400
);
}
catch(Exception $ex){
Log::error($ex);
return Response::view
(
'errors.400',
array
(
'error' => "Bad Request",
'error_description' => "Generic Error"
),
400
);
}
}
}

View File

@ -1,140 +0,0 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Utils\PagingConstants;
use App\ModelSerializers\SerializerRegistry;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use utils\Filter;
use utils\FilterParser;
use utils\OrderParser;
use utils\PagingInfo;
use Exception;
use models\exceptions\ValidationException;
use models\exceptions\EntityNotFoundException;
/**
* Trait GetAllTrait
* @package App\Http\Controllers
*/
trait GetAllTrait
{
/**
* @return array
*/
protected function getFilterRules():array{
return [];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [];
}
protected function applyExtraFilters(Filter $filter):Filter{
return $filter;
}
protected function getAllSerializerType():string{
return SerializerRegistry::SerializerType_Public;
}
/**
* @return mixed
*/
public function getAll()
{
$values = Input::all();
$rules = [
'page' => 'integer|min:1',
'per_page' => sprintf('required_with:page|integer|min:%s|max:%s', PagingConstants::MinPageSize, PagingConstants::MaxPageSize),
];
try {
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = PagingConstants::DefaultPageSize;;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), $this->getFilterRules());
}
if(is_null($filter)) $filter = new Filter();
$filter_validator_rules = $this->getFilterValidatorRules();
if(count($filter_validator_rules)) {
$filter->validate($filter_validator_rules);
}
$order = null;
if (Input::has('order'))
{
$order = OrderParser::parse(Input::get('order'), $this->getOrderRules());
}
$data = $this->repository->getAllByPage(new PagingInfo($page, $per_page), $this->applyExtraFilters($filter), $order);
return $this->ok
(
$data->toArray
(
Input::get('expand', ''),
[],
[],
[],
$this->getAllSerializerType()
)
);
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,472 +0,0 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\OpenId\DiscoveryController;
use App\Http\Controllers\OpenId\OpenIdController;
use App\Http\Utils\CountryList;
use Auth\Exceptions\AuthenticationException;
use Auth\Exceptions\UnverifiedEmailMemberException;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use OAuth2\Repositories\IApiScopeRepository;
use OAuth2\Repositories\IClientRepository;
use OpenId\Services\IUserService;
use OAuth2\Services\IApiScopeService;
use OAuth2\Services\IClientService;
use OAuth2\Services\IMementoOAuth2SerializerService;
use OAuth2\Services\IResourceServerService;
use OAuth2\Services\ISecurityContextService;
use OAuth2\Services\ITokenService;
use OpenId\Services\IMementoOpenIdSerializerService;
use OpenId\Services\ITrustedSitesService;
use models\exceptions\ValidationException;
use Services\IUserActionService;
use Sokil\IsoCodes\IsoCodesFactory;
use Strategies\DefaultLoginStrategy;
use Strategies\IConsentStrategy;
use Strategies\OAuth2ConsentStrategy;
use Strategies\OAuth2LoginStrategy;
use Strategies\OpenIdConsentStrategy;
use Strategies\OpenIdLoginStrategy;
use Utils\IPHelper;
use Utils\Services\IAuthService;
use Utils\Services\IServerConfigurationService;
use Utils\Services\IServerConfigurationService as IUtilsServerConfigurationService;
/**
* Class UserController
* @package App\Http\Controllers
*/
final class UserController extends OpenIdController
{
/**
* @var IMementoOpenIdSerializerService
*/
private $openid_memento_service;
/**
* @var IMementoOAuth2SerializerService
*/
private $oauth2_memento_service;
/**
* @var IAuthService
*/
private $auth_service;
/**
* @var IServerConfigurationService
*/
private $server_configuration_service;
/**
* @var DiscoveryController
*/
private $discovery;
/**
* @var IUserService
*/
private $user_service;
/**
* @var IUserActionService
*/
private $user_action_service;
/**
* @var DefaultLoginStrategy
*/
private $login_strategy;
/**
* @var IConsentStrategy
*/
private $consent_strategy;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IApiScopeRepository
*/
private $scope_repository;
/**
* @var ITokenService
*/
private $token_service;
/**
* @var IResourceServerService
*/
private $resource_server_service;
/**
* @var IUtilsServerConfigurationService
*/
private $utils_configuration_service;
/**
* @var ISecurityContextService
*/
private $security_context_service;
/**
* UserController constructor.
* @param IMementoOpenIdSerializerService $openid_memento_service
* @param IMementoOAuth2SerializerService $oauth2_memento_service
* @param IAuthService $auth_service
* @param IUtilsServerConfigurationService $server_configuration_service
* @param ITrustedSitesService $trusted_sites_service
* @param DiscoveryController $discovery
* @param IUserService $user_service
* @param IUserActionService $user_action_service
* @param IClientRepository $client_repository
* @param IApiScopeRepository $scope_repository
* @param ITokenService $token_service
* @param IResourceServerService $resource_server_service
* @param IUtilsServerConfigurationService $utils_configuration_service
* @param ISecurityContextService $security_context_service
*/
public function __construct
(
IMementoOpenIdSerializerService $openid_memento_service,
IMementoOAuth2SerializerService $oauth2_memento_service,
IAuthService $auth_service,
IServerConfigurationService $server_configuration_service,
ITrustedSitesService $trusted_sites_service,
DiscoveryController $discovery,
IUserService $user_service,
IUserActionService $user_action_service,
IClientRepository $client_repository,
IApiScopeRepository $scope_repository,
ITokenService $token_service,
IResourceServerService $resource_server_service,
IUtilsServerConfigurationService $utils_configuration_service,
ISecurityContextService $security_context_service
)
{
$this->openid_memento_service = $openid_memento_service;
$this->oauth2_memento_service = $oauth2_memento_service;
$this->auth_service = $auth_service;
$this->server_configuration_service = $server_configuration_service;
$this->trusted_sites_service = $trusted_sites_service;
$this->discovery = $discovery;
$this->user_service = $user_service;
$this->user_action_service = $user_action_service;
$this->client_repository = $client_repository;
$this->scope_repository = $scope_repository;
$this->token_service = $token_service;
$this->resource_server_service = $resource_server_service;
$this->utils_configuration_service = $utils_configuration_service;
$this->security_context_service = $security_context_service;
$this->middleware(function ($request, $next) {
if ($this->openid_memento_service->exists())
{
//openid stuff
$this->login_strategy = new OpenIdLoginStrategy
(
$this->openid_memento_service,
$this->user_action_service,
$this->auth_service
);
$this->consent_strategy = new OpenIdConsentStrategy
(
$this->openid_memento_service,
$this->auth_service,
$this->server_configuration_service,
$this->user_action_service
);
}
else if ($this->oauth2_memento_service->exists())
{
$this->login_strategy = new OAuth2LoginStrategy
(
$this->auth_service,
$this->oauth2_memento_service,
$this->user_action_service,
$this->security_context_service
);
$this->consent_strategy = new OAuth2ConsentStrategy
(
$this->auth_service,
$this->oauth2_memento_service,
$this->scope_repository,
$this->client_repository
);
}
else
{
//default stuff
$this->login_strategy = new DefaultLoginStrategy($this->user_action_service, $this->auth_service);
$this->consent_strategy = null;
}
return $next($request);
});
}
public function getLogin()
{
return $this->login_strategy->getLogin();
}
public function cancelLogin()
{
return $this->login_strategy->cancelLogin();
}
public function postLogin()
{
$max_login_attempts_2_show_captcha = $this->server_configuration_service->getConfigValue("MaxFailed.LoginAttempts.2ShowCaptcha");
$login_attempts = 0;
$username = '';
try
{
$data = Input::all();
if(isset($data['username']))
$data['username'] = trim($data['username']);
if(isset($data['password']))
$data['password'] = trim($data['password']);
$login_attempts = intval(Input::get('login_attempts'));
// Build the validation constraint set.
$rules = array
(
'username' => 'required|email',
'password' => 'required',
);
if ($login_attempts >= $max_login_attempts_2_show_captcha)
{
$rules['g-recaptcha-response'] = 'required|recaptcha';
}
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if ($validator->passes())
{
$username = $data['username'];
$password = $data['password'];
$remember = Input::get("remember");
$remember = !is_null($remember);
if ($this->auth_service->login($username, $password, $remember))
{
return $this->login_strategy->postLogin();
}
//failed login attempt...
$user = $this->auth_service->getUserByUsername($username);
if (!is_null($user))
{
$login_attempts = $user->getLoginFailedAttempt();
}
return $this->login_strategy->errorLogin
(
array
(
'max_login_attempts_2_show_captcha' => $max_login_attempts_2_show_captcha,
'login_attempts' => $login_attempts,
'username' => $username,
'error_message' => "We are sorry, your username or password does not match an existing record."
)
);
}
// validator errors
return $this->login_strategy->errorLogin
(
array
(
'max_login_attempts_2_show_captcha' => $max_login_attempts_2_show_captcha,
'login_attempts' => $login_attempts,
'validator' => $validator
)
);
}
catch(UnverifiedEmailMemberException $ex1)
{
Log::warning($ex1);
return $this->login_strategy->errorLogin
(
array
(
'max_login_attempts_2_show_captcha' => $max_login_attempts_2_show_captcha,
'login_attempts' => $login_attempts,
'username' => $username,
'error_message' => $ex1->getMessage()
)
);
}
catch(AuthenticationException $ex2){
Log::warning($ex2);
return Redirect::action('UserController@getLogin');
}
catch (Exception $ex)
{
Log::error($ex);
return Redirect::action('UserController@getLogin');
}
}
public function getConsent()
{
if (is_null($this->consent_strategy))
{
return View::make("errors.400");
}
return $this->consent_strategy->getConsent();
}
public function postConsent()
{
try
{
$data = Input::all();
$rules = array
(
'trust' => 'required|oauth2_trust_response',
);
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if ($validator->passes())
{
if (is_null($this->consent_strategy))
{
return View::make("errors.404");
}
return $this->consent_strategy->postConsent(Input::get("trust"));
}
return Redirect::action('UserController@getConsent')->withErrors($validator);
}
catch (Exception $ex)
{
Log::error($ex);
return Redirect::action('UserController@getConsent');
}
}
public function getIdentity($identifier)
{
try
{
$user = $this->auth_service->getUserByOpenId($identifier);
if (is_null($user))
{
return View::make("errors.404");
}
if ($this->isDiscoveryRequest())
{
/*
* If the Claimed Identifier was not previously discovered by the Relying Party
* (the "openid.identity" in the request was "http://specs.openid.net/auth/2.0/identifier_select"
* or a different Identifier, or if the OP is sending an unsolicited positive assertion),
* the Relying Party MUST perform discovery on the Claimed Identifier in
* the response to make sure that the OP is authorized to make assertions about the Claimed Identifier.
*/
return $this->discovery->user($identifier);
}
$redirect = Session::get('backurl');
if (!empty($redirect)) {
Session::forget('backurl');
Session::save();
return Redirect::to($redirect);
}
$current_user = $this->auth_service->getCurrentUser();
$another_user = false;
if ($current_user && $current_user->getIdentifier() != $user->getIdentifier())
{
$another_user = true;
}
$assets_url = $this->utils_configuration_service->getConfigValue("Assets.Url");
$pic_url = $user->getPic();
$pic_url = str_contains($pic_url, 'http') ? $pic_url : $assets_url . $pic_url;
$params = [
'show_fullname' => $user->getShowProfileFullName(),
'username' => $user->getFullName(),
'show_email' => $user->getShowProfileEmail(),
'email' => $user->getEmail(),
'identifier' => $user->getIdentifier(),
'show_pic' => $user->getShowProfilePic(),
'pic' => $pic_url,
'another_user' => $another_user,
];
return View::make("identity", $params);
}
catch (Exception $ex)
{
Log::error($ex);
return View::make("errors.404");
}
}
public function logout()
{
$this->user_action_service->addUserAction
(
$this->auth_service->getCurrentUser()->getId(),
IPHelper::getUserIp(),
IUserActionService::LogoutAction
);
$this->auth_service->logout();
Session::flush();
Session::regenerate();
return Redirect::action("UserController@getLogin");
}
public function getProfile()
{
$user = $this->auth_service->getCurrentUser();
$sites = $user->getTrustedSites();
$actions = $user->getLatestNActions(10);
// init database
$isoCodes = new IsoCodesFactory();
// get languages database
$languages = $isoCodes->getLanguages()->toArray();
$lang2Code = [];
foreach ($languages as $lang){
if(!empty($lang->getAlpha2()))
$lang2Code[] = $lang;
}
return View::make("profile", [
'user' => $user,
"openid_url" => $this->server_configuration_service->getUserIdentityEndpointURL($user->getIdentifier()),
"sites" => $sites,
'actions' => $actions,
'countries' => CountryList::getCountries(),
'languages' => $lang2Code,
]);
}
public function deleteTrustedSite($id)
{
$this->trusted_sites_service->delete($id);
return Redirect::action("UserController@getProfile");
}
}

View File

@ -1,80 +0,0 @@
<?php namespace App\Http;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Middleware\CookiesSameSiteNoneKnownIncompatibleClients;
use App\Http\Middleware\SecurityHTTPHeadersWriterMiddleware;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
/**
* Class Kernel
* @package App\Http
*/
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\SingleAccessPoint::class,
\Spatie\Cors\Cors::class,
\App\Http\Middleware\ParseMultipartFormDataInputForNonPostRequests::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
CookiesSameSiteNoneKnownIncompatibleClients::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
SecurityHTTPHeadersWriterMiddleware::class,
],
'api' => [
'ssl',
'oauth2.endpoint',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'ssl' => \App\Http\Middleware\SSLMiddleware::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'csrf' => \App\Http\Middleware\VerifyCsrfToken::class,
'oauth2.endpoint' => \App\Http\Middleware\OAuth2BearerAccessTokenRequestValidator::class,
'oauth2.currentuser.serveradmin' => \App\Http\Middleware\CurrentUserIsOAuth2ServerAdmin::class,
'oauth2.currentuser.serveradmin.json' => \App\Http\Middleware\CurrentUserIsOAuth2ServerAdminJson::class,
'openstackid.currentuser.serveradmin' => \App\Http\Middleware\CurrentUserIsOpenIdServerAdmin::class,
'openstackid.currentuser.serveradmin.json' => \App\Http\Middleware\CurrentUserIsOpenIdServerAdminJson::class,
'oauth2.currentuser.allow.client.edition' => \App\Http\Middleware\CurrentUserCanEditOAuth2Client::class,
'oauth2.currentuser.owns.client' => \App\Http\Middleware\CurrentUserOwnsOAuth2Client::class,
];
}

View File

@ -1,49 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
/**
* Class Authenticate
* @package App\Http\Middleware
*/
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
Session::put('backurl', URL::full());
Session::save();
return Redirect::action('UserController@getLogin');
}
$redirect = Session::get('backurl');
if (!empty($redirect)) {
Session::forget('backurl');
Session::save();
return Redirect::to($redirect);
}
return $next($request);
}
}

View File

@ -1,381 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Utils\Services\ICacheService;
use OAuth2\Models\IApiEndpoint;
use OAuth2\Repositories\IApiEndpointRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
use libs\utils\RequestUtils;
/**
*
* @package App\Http\Middleware\
* Implementation of http://www.w3.org/TR/cors/
*/
final class CORSMiddleware
{
private $headers = [];
/**
* A header is said to be a simple header if the header field name is an ASCII case-insensitive match for Accept,
* Accept-Language, or Content-Language or if it is an ASCII case-insensitive match for Content-Type and the header
* field value media type (excluding parameters) is an ASCII case-insensitive match for
* application/x-www-form-urlencoded, multipart/form-data, or text/plain.
*/
protected static $simple_headers = array
(
'accept',
'accept-language',
'content-language',
'origin',
);
protected static $simple_content_header_values = array(
'application/x-www-form-urlencode',
'multipart/form-data',
'text/plain');
/**
* A method is said to be a simple method if it is a case-sensitive match for one of the following:
* - GET
* - HEAD
* - POST
*/
protected static $simple_http_methods = array('GET', 'HEAD', 'POST');
const DefaultAllowedHeaders = 'origin, content-type, accept, authorization, x-requested-with';
const DefaultAllowedMethods = 'GET, POST, OPTIONS, PUT, DELETE';
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var IApiEndpoint;
*/
private $current_endpoint = null;
private $allowed_headers;
private $allowed_methods;
/**
* @var ICacheService
*/
private $cache_service;
public function __construct(IApiEndpointRepository $endpoint_repository, ICacheService $cache_service)
{
$this->endpoint_repository = $endpoint_repository;
$this->cache_service = $cache_service;
$this->allowed_headers = Config::get('cors.allowed_headers', self::DefaultAllowedHeaders);
$this->allowed_methods = Config::get('cors.allowed_methods', self::DefaultAllowedMethods);
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($response = $this->preProcess($request)) {
return $response;
}
//normal processing
$response = $next($request);
$this->postProcess($request, $response);
return $response;
}
private function generatePreflightCacheKey($request)
{
$cache_id = 'pre-flight-' . $request->getClientIp() . '-' . $request->getRequestUri() . '-' . $request->getMethod();
return $cache_id;
}
/**
* @param Request $request
* @return Response
*/
public function preProcess(Request $request)
{
$actual_request = false;
if ($this->isValidCORSRequest($request)) {
/* Step 01 : Determine the type of the incoming request */
$type = $this->getRequestType($request);
/* Step 02 : Process request according to is type */
switch ($type) {
case CORSRequestPreflightType::REQUEST_FOR_PREFLIGHT: {
// HTTP request send by client to preflight a further 'Complex' request
// sets the original method on request in order to be able to find the
// correct route
$real_method = $request->headers->get('Access-Control-Request-Method');
$route_path = RequestUtils::getCurrentRoutePath($request);
if (strpos($route_path, '/') != 0)
$route_path = '/' . $route_path;
$request->setMethod($real_method);
if (!$route_path || !$this->checkEndPoint($route_path, $real_method)) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
// ----Step 2b: Store pre-flight request data in the Cache to keep (mark) the request as correctly followed the request pre-flight process
$data = new CORSRequestPreflightData($request, $this->current_endpoint->supportCredentials());
$cache_id = $this->generatePreflightCacheKey($request);
$this->cache_service->storeHash($cache_id, $data->toArray(), CORSRequestPreflightData::$cache_lifetime);
// ----Step 2c: Return corresponding response - This part should be customized with application specific constraints.....
return $this->makePreflightResponse($request);
}
break;
case CORSRequestPreflightType::COMPLEX_REQUEST: {
$cache_id = $this->generatePreflightCacheKey($request);; // ----Step 2a: Check if the current request has an entry into the preflighted requests Cache
$data = $this->cache_service->getHash($cache_id, CORSRequestPreflightData::$cache_attributes);
if (!count($data)) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
// ----Step 2b: Check that pre-flight information declared during the pre-flight request match the current request on key information
$match = false;
// ------Start with comparison of "Origin" HTTP header (according to utility method impl. used to retrieve header reference cannot be null)...
if ($request->headers->get('Origin') === $data['origin']) {
// ------Continue with HTTP method...
if ($request->getMethod() === $data['expected_method']) {
// ------Finish with custom HTTP headers (use an method to avoid manual iteration on collection to increase the speed)...
$x_headers = self::getCustomHeaders($request);
$x_headers_pre = explode(',', $data['expected_custom_headers']);
sort($x_headers);
sort($x_headers_pre);
if (count(array_diff($x_headers, $x_headers_pre)) === 0) {
$match = true;
}
}
}
if (!$match) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
$actual_request = true;
}
break;
case CORSRequestPreflightType::SIMPLE_REQUEST: {
// origins, do not set any additional headers and terminate this set of steps.
if (!$this->isAllowedOrigin($request)) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
$actual_request = true;
// If the resource supports credentials add a single Access-Control-Allow-Origin header, with the value
// of the Origin header as value, and add a single Access-Control-Allow-Credentials header with the
// case-sensitive string "true" as value.
// Otherwise, add a single Access-Control-Allow-Origin header, with either the value of the Origin header
// or the string "*" as value.
}
break;
}
}
if ($actual_request) {
// Save response headers
$cache_id = $this->generatePreflightCacheKey($request);
// ----Step 2a: Check if the current request has an entry into the preflighted requests Cache
$data = $this->cache_service->getHash($cache_id, CORSRequestPreflightData::$cache_attributes);
$this->headers['Access-Control-Allow-Origin'] = $request->headers->get('Origin');
if ((isset($data['allows_credentials']) && (bool)$data['allows_credentials'])) {
$this->headers['Access-Control-Allow-Credentials'] = 'true';
}
/**
* During a CORS request, the getResponseHeader() method can only access simple response headers.
* Simple response headers are defined as follows:
** Cache-Control
** Content-Language
** Content-Type
** Expires
** Last-Modified
** Pragma
* If you want clients to be able to access other headers,
* you have to use the Access-Control-Expose-Headers header.
* The value of this header is a comma-delimited list of response headers you want to expose
* to the client.
*/
$exposed_headers = Config::get('cors.exposed_headers', 'Content-Type, Expires');
if (!empty($exposed_headers)) {
$this->headers['Access-Control-Expose-Headers'] = $exposed_headers;
}
}
}
public function postProcess(Request $request, Response $response)
{
// add CORS response headers
if (count($this->headers) > 0) {
$response->headers->add($this->headers);
}
return $response;
}
/**
* @param Request $request
* @return Response
*/
private function makePreflightResponse(Request $request)
{
$response = new Response();
if (!$this->isAllowedOrigin($request)) {
$response->headers->set('Access-Control-Allow-Origin', 'null');
$response->setStatusCode(403);
return $response;
}
$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));
// The Access-Control-Request-Method header indicates which method will be used in the actual
// request as part of the preflight request
// check request method
if ($request->headers->get('Access-Control-Request-Method') != $this->current_endpoint->getHttpMethod()) {
$response->setStatusCode(405);
return $response;
}
// The Access-Control-Allow-Credentials header indicates whether the response to request
// can be exposed when the omit credentials flag is unset. When part of the response to a preflight request
// it indicates that the actual request can include user credentials.
if ($this->current_endpoint->supportCredentials()) {
$response->headers->set('Access-Control-Allow-Credentials', 'true');
}
if (Config::get('cors.use_pre_flight_caching', false)) {
// The Access-Control-Max-Age header indicates how long the response can be cached, so that for
// subsequent requests, within the specified time, no preflight request has to be made.
$response->headers->set('Access-Control-Max-Age', Config::get('cors.max_age', 32000));
}
// The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request,
// which header field names can be used during the actual request
$response->headers->set('Access-Control-Allow-Headers', $this->allowed_headers);
//The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request,
// which methods can be used during the actual request.
$response->headers->set('Access-Control-Allow-Methods', $this->allowed_methods);
// The Access-Control-Request-Headers header indicates which headers will be used in the actual request
// as part of the preflight request.
$headers = $request->headers->get('Access-Control-Request-Headers');
if ($headers) {
$headers = trim(strtolower($headers));
$allow_headers = explode(', ', $this->allowed_headers);
foreach (preg_split('{, *}', $headers) as $header) {
//if they are simple headers then skip them
if (in_array($header, self::$simple_headers, true)) {
continue;
}
//check is the requested header is on the list of allowed headers
if (!in_array($header, $allow_headers, true)) {
$response->setStatusCode(400);
$response->setContent('Unauthorized header ' . $header);
break;
}
}
}
//OK - No Content
$response->setStatusCode(204);
return $response;
}
/**
* @param Request $request
* @returns bool
*/
private function isValidCORSRequest(Request $request)
{
/**
* The presence of the Origin header does not necessarily mean that the request is a cross-origin request.
* While all cross-origin requests will contain an Origin header,
* Origin header on same-origin requests. But Chrome and Safari include an Origin header on
* same-origin POST/PUT/DELETE requests (same-origin GET requests will not have an Origin header).
*/
return $request->headers->has('Origin');
}
private function checkEndPoint($endpoint_path, $http_method)
{
$this->current_endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($endpoint_path, $http_method);
if (is_null($this->current_endpoint)) {
return false;
}
if (!$this->current_endpoint->supportCORS() || !$this->current_endpoint->isActive()) {
return false;
}
return true;
}
/**
* @param string $origin
* @return bool
*/
private function isAllowedOrigin($origin)
{
return true;
}
private static function getRequestType(Request $request)
{
$type = CORSRequestPreflightType::UNKNOWN;
$http_method = $request->getMethod();
$content_type = strtolower($request->getContentType());
$http_method = strtoupper($http_method);
if ($http_method === 'OPTIONS' && $request->headers->has('Access-Control-Request-Method')) {
$type = CORSRequestPreflightType::REQUEST_FOR_PREFLIGHT;
} else {
if (self::hasCustomHeaders($request)) {
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
} elseif ($http_method === 'POST' && !in_array($content_type, self::$simple_content_header_values, true)) {
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
} elseif (!in_array($http_method, self::$simple_http_methods, true)) {
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
} else {
$type = CORSRequestPreflightType::SIMPLE_REQUEST;
}
}
return $type;
}
private static function getCustomHeaders(Request $request)
{
$custom_headers = [];
foreach ($request->headers->all() as $k => $h) {
if (starts_with('X-', strtoupper(trim($k)))) {
array_push($custom_headers, strtoupper(trim($k)));
}
}
return $custom_headers;
}
private static function hasCustomHeaders(Request $request)
{
return count(self::getCustomHeaders($request)) > 0;
}
}

View File

@ -1,82 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Symfony\Component\HttpFoundation\Request;
/**
* Class CORSRequestPreflightData
* @package App\Http\Middleware
*/
class CORSRequestPreflightData
{
// ttl on seconds
public static $cache_lifetime = 10;
public static $cache_attributes = array('sender', 'uri', 'origin', 'expected_method', 'expected_custom_headers', 'allows_credentials');
/** Final HTTP request expected method */
private $expected_method = null;
/** Final HTTP request expected custom headers */
private $expected_custom_headers = [];
/** Current HTTP request uri */
private $uri = null;
/** Current HTTP request origin header */
private $origin = null;
/** Current Sender IP address */
private $sender = null;
/**
* @var bool
*/
private $allows_credentials;
/**
* @param Request $request
* @param bool $allows_credentials
*/
public function __construct(Request $request, $allows_credentials)
{
$this->sender = $request->getClientIp();
$this->uri = $request->getRequestUri();
$this->origin = $request->headers->get('Origin');
$this->expected_method = $request->headers->get('Access-Control-Request-Method');
$this->allows_credentials = $allows_credentials;
$tmp = $request->headers->get("Access-Control-Request-Headers");
if (!empty($tmp))
{
$hs = explode(',', $tmp);
foreach ($hs as $h)
{
array_push($this->expected_custom_headers, strtoupper(trim($h)));
}
}
}
/**
* @return array
*/
public function toArray()
{
$res = [];
$res['sender'] = $this->sender;
$res['uri'] = $this->uri;
$res['origin'] = $this->origin;
$res['allows_credentials'] = $this->allows_credentials;
$res['expected_method'] = $this->expected_method;
$res['expected_custom_headers'] = implode(',', $this->expected_custom_headers);
return $res;
}
}

View File

@ -1,36 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class CORSRequestPreflightType
* @package App\Http\Middleware
*/
final class CORSRequestPreflightType
{
/** HTTP request send by client to preflight a further 'Complex' request */
const REQUEST_FOR_PREFLIGHT = 0;
/** Normal HTTP request send by client that require preflight ie 'Complex' resquest in Preflight process */
const COMPLEX_REQUEST = 1;
/** Normal HTTP request send by client that do not require preflight ie 'Simple' resquest in Preflight process */
const SIMPLE_REQUEST = 2;
/** Cannot determine request type */
const UNKNOWN = -1;
}

View File

@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -1,65 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Utils\CookieSameSitePolicy;
use Closure;
use Symfony\Component\HttpFoundation\Cookie;
/**
* Class CookiesSameSiteNoneKnownIncompatibleClients
* @package App\Http\Middleware
*/
class CookiesSameSiteNoneKnownIncompatibleClients
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
// check if user agent is compatible or not with SameSite=None
// https://www.chromium.org/updates/same-site/incompatible-clients
foreach ($response->headers->getCookies() as $cookie) {
$sameSite = $cookie->getSameSite();
if($sameSite == Cookie::SAMESITE_NONE){
// check if we could use it or not
if(CookieSameSitePolicy::isSameSiteNoneIncompatible()){
// replace the cookie with a compatible version ( unset sameSite value)
// make a clone
$compatibleCookie = Cookie::create
(
$cookie->getName(),
$cookie->getValue(),
$cookie->getExpiresTime(),
$cookie->getPath(),
$cookie->getDomain(),
$cookie->isSecure(),
$cookie->isHttpOnly(),
$cookie->isRaw(),
null
);
// and overwrite it
$response->headers->setCookie($compatibleCookie);
}
}
}
return $response;
}
}

View File

@ -1,81 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Response;
use OAuth2\Repositories\IClientRepository;
use Utils\Services\IAuthService;
use Utils\Services\ServiceLocator;
use Utils\Services\UtilsServiceCatalog;
use OAuth2\Services\OAuth2ServiceCatalog;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
/**
* Class CurrentUserCanEditOAuth2Client
* @package App\Http\Middleware
*/
final class CurrentUserCanEditOAuth2Client
{
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IAuthService
*/
private $auth_service;
public function __construct(IClientRepository $client_repository, IAuthService $auth_service)
{
$this->client_repository = $client_repository;
$this->auth_service = $auth_service;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
try{
$route = Route::getCurrentRoute();
$client_id = $route->parameter('id');
if(is_null($client_id))
$client_id = $route->parameter('client_id');
if(is_null($client_id))
$client_id = Input::get('client_id',null);;
$client = $this->client_repository->getClientByIdentifier($client_id);
$user = $this->auth_service->getCurrentUser();
if (is_null($client) || !$client->canEdit($user))
throw new Exception('invalid client id for current user');
} catch (Exception $ex) {
Log::error($ex);
return Response::json(array('error' => 'operation not allowed.'), 400);
}
return $next($request);
}
}

View File

@ -1,44 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
/**
* Class CurrentUserIsOAuth2ServerAdmin
* @package App\Http\Middleware
*/
final class CurrentUserIsOAuth2ServerAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
return Response::view('errors.404', [], 404);
}
if(!Auth::user()->isOAuth2ServerAdmin())
{
return Response::view('errors.404', [], 404);
}
return $next($request);
}
}

View File

@ -1,45 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
/**
* Class CurrentUserIsOAuth2ServerAdminJson
* @package App\Http\Middleware
*/
final class CurrentUserIsOAuth2ServerAdminJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
return Response::json(array('error' => 'you are not allowed to perform this operation'), 403);
}
if(!Auth::user()->isOAuth2ServerAdmin())
{
return Response::json(array('error' => 'you are not allowed to perform this operation'), 403);
}
return $next($request);
}
}

View File

@ -1,44 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
/**
* Class CurrentUserIsOpenIdServerAdmin
* @package App\Http\Middleware
*/
final class CurrentUserIsOpenIdServerAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
return Response::view('errors.404', [], 404);
}
if(!Auth::user()->isOpenIdServerAdmin())
{
return Response::view('errors.404', [], 404);
}
return $next($request);
}
}

View File

@ -1,44 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
/**
* Class CurrentUserIsOpenIdServerAdminJson
* @package App\Http\Middleware
*/
class CurrentUserIsOpenIdServerAdminJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
return Response::json(['error' => 'you are not allowed to perform this operation']);
}
if(!Auth::user()->isOpenIdServerAdmin())
{
return Response::json(['error' => 'you are not allowed to perform this operation']);
}
return $next($request);
}
}

View File

@ -1,80 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Response;
use OAuth2\Repositories\IClientRepository;
use Utils\Services\IAuthService;
use Utils\Services\ServiceLocator;
use Utils\Services\UtilsServiceCatalog;
use OAuth2\Services\OAuth2ServiceCatalog;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
/**
* Class CurrentUserOwnsOAuth2Client
* @package App\Http\Middleware
*/
class CurrentUserOwnsOAuth2Client
{
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IAuthService
*/
private $auth_service;
public function __construct(IClientRepository $client_repository, IAuthService $auth_service)
{
$this->client_repository = $client_repository;
$this->auth_service = $auth_service;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
try{
$route = Route::getCurrentRoute();
$client_id = $route->parameter('id');
if(is_null($client_id))
$client_id = $route->parameter('client_id');
if(is_null($client_id))
$client_id = Input::get('client_id',null);;
$client = $this->client_repository->getClientByIdentifier($client_id);
$user = $this->auth_service->getCurrentUser();
if (is_null($client) || !$client->isOwner($user))
throw new Exception('invalid client id for current user');
} catch (Exception $ex) {
Log::error($ex);
return Response::json(array('error' => 'operation not allowed.'), 400);
}
return $next($request);
}
}

View File

@ -1,51 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Log;
/**
* Class ETagsMiddleware
* @package App\Http\Middleware
*/
final class ETagsMiddleware
{
/**
* Handle an incoming request.
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response->getStatusCode() === 200 && $request->getMethod() === 'GET')
{
$etag = md5($response->getContent());
$requestETag = str_replace('"', '', $request->getETags());
$requestETag = str_replace('-gzip', '', $requestETag);
if ($requestETag && $requestETag[0] == $etag)
{
Log::debug('ETAG 304');
$response->setNotModified();
}
$response->setEtag($etag);
}
return $response;
}
}

View File

@ -1,59 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
use OAuth2\Services\IPrincipalService;
use Symfony\Component\HttpFoundation\Request;
/**
* Class EncryptCookies
* @package App\Http\Middleware
*/
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
IPrincipalService::OP_BROWSER_STATE_COOKIE_NAME
];
/**
* Decrypt the cookies on the request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @return \Symfony\Component\HttpFoundation\Request
*/
protected function decrypt(Request $request)
{
foreach ($request->cookies as $key => $cookie) {
if ($this->isDisabled($key)) {
continue;
}
try {
$request->cookies->set($key, $this->decryptCookie($key, $cookie));
} catch (DecryptException $e) {
$request->cookies->set($key, null);
}
catch(\ErrorException $e1){
$request->cookies->set($key, null);
}
}
return $request;
}
}

View File

@ -1,350 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use OAuth2\BearerAccessTokenAuthorizationHeaderParser;
use OAuth2\Exceptions\ExpiredAccessTokenException;
use OAuth2\Exceptions\InvalidGrantTypeException;
use OAuth2\Exceptions\RevokedAccessTokenException;
use OAuth2\Models\IClient;
use OAuth2\OAuth2Protocol;
use OAuth2\Exceptions\OAuth2ResourceServerException;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Responses\OAuth2WWWAuthenticateErrorResponse;
use OAuth2\Services\ITokenService;
use OAuth2\IResourceServerContext;
use OAuth2\Repositories\IApiEndpointRepository;
use URL\Normalizer;
use Exception;
use Utils\Services\ICheckPointService;
use Utils\Services\ILogService;
use libs\utils\RequestUtils;
/**
* Class OAuth2BearerAccessTokenRequestValidator
* this class implements the logic to Accessing to Protected Resources
* @see http://tools.ietf.org/html/rfc6750
* @see http://tools.ietf.org/html/rfc6749#section-7
* @package App\Http\Middleware
*/
final class OAuth2BearerAccessTokenRequestValidator
{
/**
* @var IResourceServerContext
*/
private $context;
/**
* @var array
*/
private $headers;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var ITokenService
*/
private $token_service;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var ILogService
*/
private $log_service;
/**
* @var ICheckPointService
*/
private $checkpoint_service;
/**
* OAuth2BearerAccessTokenRequestValidator constructor.
* @param IResourceServerContext $context
* @param IApiEndpointRepository $endpoint_repository
* @param ITokenService $token_service
* @param IClientRepository $client_repository
* @param ILogService $log_service
* @param ICheckPointService $checkpoint_service
*/
public function __construct(
IResourceServerContext $context,
IApiEndpointRepository $endpoint_repository,
ITokenService $token_service,
IClientRepository $client_repository,
ILogService $log_service,
ICheckPointService $checkpoint_service
) {
$this->context = $context;
$this->headers = $this->getHeaders();
$this->endpoint_repository = $endpoint_repository;
$this->token_service = $token_service;
$this->client_repository = $client_repository;
$this->log_service = $log_service;
$this->checkpoint_service = $checkpoint_service;
}
/**
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @return OAuth2WWWAuthenticateErrorResponse
*/
public function handle($request, Closure $next)
{
Log::debug(sprintf("OAuth2BearerAccessTokenRequestValidator::handle %s %s", $request->getMethod(), $request->getRequestUri()));
$url = $request->getRequestUri();
$method = $request->getMethod();
$realm = $request->getHost();
try {
$route_path = RequestUtils::getCurrentRoutePath($request);
if (strpos($route_path, '/') != 0)
$route_path = '/' . $route_path;
if (!$route_path) {
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
sprintf('API endpoint does not exits! (%s:%s)', $url, $method)
);
}
Log::debug($request->headers->__toString());
// http://tools.ietf.org/id/draft-abarth-origin-03.html
$origin = $request->headers->has('Origin') ? $request->headers->get('Origin') : null;
if (!empty($origin)) {
$nm = new Normalizer($origin);
$origin = $nm->normalize();
}
//check first http basic auth header
$auth_header = isset($this->headers['authorization']) ? $this->headers['authorization'] : null;
if (!is_null($auth_header) && !empty($auth_header)) {
$access_token_value = BearerAccessTokenAuthorizationHeaderParser::getInstance()->parse($auth_header);
} else {
// http://tools.ietf.org/html/rfc6750#section-2- 2
// if access token is not on authorization header check on POST/GET params
$access_token_value = Input::get(OAuth2Protocol::OAuth2Protocol_AccessToken, '');
}
if (is_null($access_token_value) || empty($access_token_value)) {
//if access token value is not set, then error
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'missing access token'
);
}
$endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($route_path, $method);
//api endpoint must be registered on db and active
if (is_null($endpoint) || !$endpoint->isActive()) {
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
sprintf('API endpoint does not exits! (%s:%s)', $route_path, $method)
);
}
$access_token = $this->token_service->getAccessToken($access_token_value);
//check lifetime
if (is_null($access_token)) {
throw new InvalidGrantTypeException(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken);
}
Log::debug(sprintf("token lifetime %s", $access_token->getRemainingLifetime()));
//check token audience
Log::debug('checking token audience ...');
$audience = explode(' ', $access_token->getAudience());
if ((!in_array($realm, $audience))) {
throw new InvalidGrantTypeException(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken);
}
//check client existence
$client_id = $access_token->getClientId();
$client = $this->client_repository->getClientById($client_id);
if(is_null($client))
throw new OAuth2ResourceServerException
(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'invalid client'
);
//if js client , then check if the origin is allowed ....
if($client->getApplicationType() == IClient::ApplicationType_JS_Client)
{
if(!empty($origin) && !$client->isOriginAllowed($origin))
throw new OAuth2ResourceServerException
(
403,
OAuth2Protocol::OAuth2Protocol_Error_UnauthorizedClient,
'invalid origin'
);
}
//check scopes
Log::debug('checking token scopes ...');
$endpoint_scopes = explode(' ', $endpoint->getScope());
$token_scopes = explode(' ', $access_token->getScope());
//check token available scopes vs. endpoint scopes
if (count(array_intersect($endpoint_scopes, $token_scopes)) == 0) {
Log::warning(
sprintf(
'access token scopes (%s) does not allow to access to api url %s , needed scopes %s',
$access_token->getScope(),
$url,
implode(' OR ', $endpoint_scopes)
)
);
throw new OAuth2ResourceServerException(
403,
OAuth2Protocol::OAuth2Protocol_Error_InsufficientScope,
'the request requires higher privileges than provided by the access token',
implode(' ', $endpoint_scopes)
);
}
Log::debug('setting resource server context ...');
//set context for api and continue processing
$context = array
(
'access_token' => $access_token_value,
'expires_in' => $access_token->getRemainingLifetime(),
'client_id' => $client_id,
'scope' => $access_token->getScope(),
'application_type' => $client->getApplicationType()
);
if (!is_null($access_token->getUserId()))
{
$context['user_id'] = $access_token->getUserId();
}
$this->context->setAuthorizationContext($context);
}
catch(OAuth2ResourceServerException $ex1)
{
$this->log_service->warning($ex1);
$this->checkpoint_service->trackException($ex1);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
$ex1->getError(),
$ex1->getErrorDescription(),
$ex1->getScope(),
$ex1->getHttpCode()
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate',$response->getWWWAuthenticateHeaderValue());
return $http_response;
}
catch(InvalidGrantTypeException $ex2)
{
$this->log_service->warning($ex2);
$this->checkpoint_service->trackException($ex2);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
'the access token provided is expired, revoked, malformed, or invalid for other reasons.',
null,
401
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate',$response->getWWWAuthenticateHeaderValue());
return $http_response;
}
catch(ExpiredAccessTokenException $ex3)
{
$this->log_service->warning($ex3);
$this->checkpoint_service->trackException($ex3);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
'the access token provided is expired, revoked, malformed, or invalid for other reasons.',
null,
401
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate',$response->getWWWAuthenticateHeaderValue());
return $http_response;
}
catch(RevokedAccessTokenException $ex4)
{
$this->log_service->warning($ex4);
$this->checkpoint_service->trackException($ex4);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
'the access token provided is expired, revoked, malformed, or invalid for other reasons.',
null,
401
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate',$response->getWWWAuthenticateHeaderValue());
return $http_response;
}
catch(Exception $ex)
{
$this->log_service->error($ex);
$this->checkpoint_service->trackException($ex);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'invalid request',
null,
400
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate',$response->getWWWAuthenticateHeaderValue());
return $http_response;
}
$response = $next($request);
return $response;
}
/**
* @return array
*/
protected function getHeaders()
{
$headers = [];
if (function_exists('getallheaders')) {
foreach (getallheaders() as $name => $value) {
$headers[strtolower($name)] = $value;
}
}
if(empty($headers)){
// @codeCoverageIgnoreEnd
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
$headers[strtolower($name)] = $value;
}
}
foreach (Request::header() as $name => $value) {
if (!array_key_exists($name, $headers)) {
$headers[strtolower($name)] = $value[0];
}
}
}
return $headers;
}
}

View File

@ -1,56 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use utils\ParseMultiPartFormDataInputStream;
use Illuminate\Support\Facades\Log;
/**
* Class ParseMultipartFormDataInputForNonPostRequests
* @package App\Http\Middleware
*/
final class ParseMultipartFormDataInputForNonPostRequests
{
/*
* Content-Type: multipart/form-data - only works for POST requests. All others fail, this is a bug in PHP since 2011.
* See comments here: https://github.com/laravel/framework/issues/13457
*
* This middleware converts all multi-part/form-data for NON-POST requests, into a properly formatted
* request variable for Laravel 5.6. It uses the ParseInputStream class, found here:
* https://gist.github.com/devmycloud/df28012101fbc55d8de1737762b70348
*/
public function handle($request, Closure $next)
{
if ($request->method() == 'POST' OR $request->method() == 'GET') {
return $next($request);
}
if (preg_match('/multipart\/form-data/', $request->headers->get('Content-Type')) or
preg_match('/multipart\/form-data/', $request->headers->get('content-type'))
) {
$parser = new ParseMultiPartFormDataInputStream(file_get_contents('php://input'));
$params = $parser->getInput();
$data = $params['parameters'];
$files = $params['files'];
if (count($files) > 0) {
Log::debug("ParseMultipartFormDataInputForNonPostRequests: files ".json_encode($files));
$request->files->add($files);
}
if (count($data) > 0) {
Log::debug("ParseMultipartFormDataInputForNonPostRequests: parameters ".json_encode($data));
$request->request->add($data);
}
}
return $next($request);
}
}

View File

@ -1,38 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
/**
* Class RedirectIfAuthenticated
* @package App\Http\Middleware
*/
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}

View File

@ -1,33 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
/**
* Class SSLMiddleware
* @package App\Http\Middleware
*/
final class SSLMiddleware
{
public function handle($request, Closure $next)
{
if (!Request::secure() && Config::get("server.ssl_enabled", false)) {
return Redirect::secure(Request::getRequestUri());
}
return $next($request);
}
}

View File

@ -1,51 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use libs\utils\RequestUtils;
/**
* Class SecurityHTTPHeadersWriterMiddleware
* https://www.owasp.org/index.php/List_of_useful_HTTP_headers
*
* @package App\Http\Middleware
*/
class SecurityHTTPHeadersWriterMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle($request, Closure $next)
{
$response = $next($request);
// https://www.owasp.org/index.php/List_of_useful_HTTP_headers
$response->headers->set('X-Content-Type-Options','nosniff');
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
$response->headers->set('X-XSS-Protection','1; mode=block');
// cache
/**
* Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate;
* and that the pragma HTTP header is set with no-cache.
*/
$response->headers->set('Pragma','no-cache');
$response->headers->set('Expires','0');
$response->headers->set('Cache-Control','no-cache, no-store, must-revalidate, private');
return $response;
}
}

View File

@ -1,49 +0,0 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Repositories\IServerConfigurationRepository;
use Closure;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Log;
use Utils\Services\ICheckPointService;
use Utils\Services\ServiceLocator;
use Utils\Services\UtilsServiceCatalog;
use Exception;
use Illuminate\Support\Facades\App;
/**
* Class SingleAccessPoint
* @package App\Http\Middleware
*/
final class SingleAccessPoint
{
public function handle($request, Closure $next)
{
// Perform action
if(Config::get('server.banning_enable', true))
{
try {
//checkpoint security pattern entry point
$checkpoint_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::CheckPointService);
if ($checkpoint_service instanceof ICheckPointService && !$checkpoint_service->check()) {
return Response::view('errors.404', [], 404);
}
} catch (Exception $ex) {
Log::error($ex);
return Response::view('errors.404', [], 404);
}
}
return $next($request);
}
}

View File

@ -1,18 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'password',
'password_confirmation',
];
}

View File

@ -1,23 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

View File

@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

View File

@ -1,10 +0,0 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
//
}

View File

@ -1,164 +0,0 @@
<?php namespace App\Http\Utils;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Log;
/**
* Class CookieSameSitePolicy
* https://www.chromium.org/updates/same-site/incompatible-clients
* @package App\Http\Utils
*/
final class CookieSameSitePolicy
{
/**
* @return bool
*/
public static function isSameSiteNoneIncompatible():bool {
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? null;
if(empty($user_agent)) return true;
Log::debug(sprintf("CookieSameSitePolicy::isSameSiteNoneIncompatible user_agent %s", $user_agent));
return self::hasWebKitSameSiteBug($user_agent) ||
self::dropsUnrecognizedSameSiteCookies($user_agent);
}
/**
* @param string $user_agent
* @return bool
*/
public static function hasWebKitSameSiteBug(string $user_agent):bool {
return self::isIosVersion($user_agent,12) ||
(self::isMacOSXVersion( $user_agent,10, 14) &&
(self::isSafari($user_agent) || self::isMacEmbeddedBrowser($user_agent)));
}
/**
* @param string $user_agent
* @param int $major
* @return bool
*/
public static function isIosVersion(string $user_agent, int $major):bool{
$parser = new Agent();
$parser->setUserAgent($user_agent);
$os = $parser->platform();
$os_version = $parser->version($os);
$os_version = explode( '_', $os_version);
return $os=="iOS" && count($os_version) > 0 && intval($os_version[0]) == $major;
}
/**
* @param string $user_agent
* @param int $major
* @param int $minor
* @return bool
*/
public static function isMacOSXVersion(string $user_agent, int $major, int $minor):bool{
$parser = new Agent();
$parser->setUserAgent($user_agent);
$os = $parser->platform();
$os_version = $parser->version($os);
$os_version = explode( '_', $os_version);
return $os == "OS X" && count($os_version) > 1 && intval($os_version[0]) == $major && intval($os_version[1]) == $minor;
}
/**
* @param string $user_agent
* @return bool
*/
public static function isSafari(string $user_agent):bool{
$parser = new Agent();
$parser->setUserAgent($user_agent);
return $parser->browser() == 'Safari';
}
/**
* @param string $user_agent
* @return bool
*/
public static function isMacEmbeddedBrowser(string $user_agent):bool{
$parser = new Agent();
$parser->setUserAgent($user_agent);
return $parser->match("^Mozilla\/[\.\d]+ \(Macintosh;.*Mac OS X [_\d]+\) AppleWebKit\/[\.\d]+ \(KHTML, like Gecko\)$");
}
/**
* @param string $user_agent
* @return bool
*/
public static function dropsUnrecognizedSameSiteCookies(string $user_agent):bool {
if(self::isUcBrowser($user_agent))
return self::isUcBrowserVersionAtLeast($user_agent, 12, 13,2);
return self::isChromiumBased($user_agent)
&& self::isChromiumVersionAtLeast($user_agent, 51)
&& !self::isChromiumVersionAtLeast($user_agent, 67);
}
/**
* @param string $user_agent
* @return bool
*/
public static function isUcBrowser(string $user_agent):bool {
$parser = new Agent();
$parser->setUserAgent($user_agent);
return $parser->browser() == 'UCBrowser';
}
/**
* @param string $user_agent
* @param int $major
* @param int $minor
* @param int $build
* @return bool
*/
public static function isUcBrowserVersionAtLeast(string $user_agent, int $major, int $minor, int $build):bool{
$parser = new Agent();
$parser->setUserAgent($user_agent);
$browser = $parser->browser();
$browser_version = $parser->version($browser);
$browser_version = explode( '.', $browser_version);
if(count($browser_version) < 3) return false;
$major_version = intval($browser_version[0]);
$minor_version = intval($browser_version[1]);
$build_version = intval($browser_version[2]);
if($browser != 'UCBrowser') return false;
if($major_version != $major)
return $major_version > $major;
if($minor_version != $minor)
return $minor_version > $minor;
return $build_version >= $build;
}
public static function isChromiumBased(string $user_agent):bool {
$parser = new Agent();
$parser->setUserAgent($user_agent);
$browser = $parser->browser();
return $browser == 'Chrome';
}
/**
* @param string $user_agent
* @param int $major
* @return bool
*/
public static function isChromiumVersionAtLeast(string $user_agent, int $major):bool {
$parser = new Agent();
$parser->setUserAgent($user_agent);
$browser = $parser->browser();
$browser_version = $parser->version($browser);
$browser_version = explode( '.', $browser_version);
if(count($browser_version) < 1) return false;
$major_version = intval($browser_version[0]);
return $browser == 'Chrome' && $major_version >= $major;
}
}

View File

@ -1,37 +0,0 @@
<?php namespace App\Http\Utils;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Sokil\IsoCodes\IsoCodesFactory;
/**
* Class CountryList
* @package App\Http\Utils
*/
final class CountryList
{
private static function countrySort($a,$b) {
$al = strtolower($a->getName());
$bl = strtolower($b->getName());
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
public static function getCountries(){
// init database
$isoCodes = new IsoCodesFactory();
$countries = $isoCodes->getCountries()->toArray();
usort($countries, array('App\Http\Utils\CountryList','countrySort'));
return $countries;
}
}

View File

@ -1,32 +0,0 @@
<?php namespace App\Http\Utils;
/**
* Copyright 2018 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use DateTime;
/**
* Class DateUtils
* @package App\Http\Utils
*/
final class DateUtils
{
/**
* @param DateTime $start1
* @param DateTime $end1
* @param DateTime $start2
* @param DateTime $end2
* @return bool
*/
public static function checkTimeFramesOverlap(DateTime $start1, DateTime $end1, DateTime $start2, DateTime $end2){
return $start1 <= $end2 && $end1 >= $start2;
}
}

View File

@ -1,24 +0,0 @@
<?php namespace App\Http\Utils;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class FileTypes
* @package App\Http\Utils
*/
final class FileTypes
{
const SlidesExtensions = ['ppt', 'pptx', 'xps', 'key', 'pdf'];
const ImagesExntesions = ['jpg', 'jpeg', 'png', 'svg', 'bmp', 'tga', 'tiff', 'gif'];
}

View File

@ -1,79 +0,0 @@
<?php namespace App\Http\Utils;
/**
* Copyright 2017 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\Model\IFolderService;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use models\main\File;
/**
* Class FileUploader
* @package App\Http\Utils
*/
final class FileUploader implements IFileUploader
{
/**
* @var IFolderService
*/
private $folder_service;
/**
* @var IBucket
*/
private $bucket;
/**
* FileUploader constructor.
* @param IFolderService $folder_service
* @param IBucket $bucket
*/
public function __construct(IFolderService $folder_service, IBucket $bucket){
$this->folder_service = $folder_service;
$this->bucket = $bucket;
}
/**
* @param UploadedFile $file
* @param $folder_name
* @param bool $is_image
* @return File
* @throws \Exception
*/
public function build(UploadedFile $file, $folder_name, $is_image = false){
$attachment = new File();
try {
$local_path = Storage::putFileAs(sprintf('/public/%s', $folder_name), $file, $file->getClientOriginalName());
$folder = $this->folder_service->findOrMake($folder_name);
$local_path = Storage::disk()->path($local_path);
$attachment->setParent($folder);
$attachment->setName($file->getClientOriginalName());
$attachment->setFilename(sprintf("assets/%s/%s", $folder_name, $file->getClientOriginalName()));
$attachment->setTitle(str_replace(array('-', '_'), ' ', preg_replace('/\.[^.]+$/', '', $file->getClientOriginalName())));
$attachment->setShowInSearch(true);
if ($is_image) // set className
$attachment->setImage();
$this->bucket->put($attachment, $local_path);
$attachment->setCloudMeta('LastPut', time());
$attachment->setCloudStatus('Live');
$attachment->setCloudSize(filesize($local_path));
}
catch (\Exception $ex){
Log::error($ex);
throw $ex;
}
return $attachment;
}
}

View File

@ -1,34 +0,0 @@
<?php namespace App\Http\Utils;
/**
* Copyright 2017 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Security\SummitScopes;
use Illuminate\Support\Facades\Config;
use models\oauth2\IResourceServerContext;
/**
* Class FilterAvailableSummitsStrategy
* @package App\Http\Utils
*/
final class FilterAvailableSummitsStrategy
{
/**
* @param IResourceServerContext $resource_server_ctx
* @return bool
*/
static public function shouldReturnAllSummits(IResourceServerContext $resource_server_ctx){
$scopes = $resource_server_ctx->getCurrentScope();
$current_realm = Config::get('app.scope_base_realm');
$needed_scope = sprintf(SummitScopes::ReadAllSummitData, $current_realm);
return in_array($needed_scope, $scopes);
}
}

Some files were not shown because too many files have changed in this diff Show More