Commit 7e21fb1c authored by Clemens John's avatar Clemens John
Browse files

Initial commit


Signed-off-by: Clemens John's avatarClemens John <clemens.john@floh1111.de>
parents
The MIT License (MIT)
Copyright (c) 2016 Clemens John
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Places Module for the Netmon API-Server
This project holds the Places module for the Netmon API-Server. It handles geographical coordinates (latitude, longitude, elevation) and administrative locations (contact information of a roof or a building in example).
## Installation
This module is automatically downloaded on the installation of the Netmon server
so you dont need to require it manually using `composer require`.
Just install and configure the module from within the root folder of
your Netmon Server installation by executing the following commands:
```
php artisan module:install Places "Netmon\Places\ModuleServiceProvider"
php artisan module:configure Places
```
## Documentation
* [Technology stack](doc/technology.md)
* [Unittesting](doc/unittesting.md)
* [Creating a release](doc/release.md)
# Contributing
## Submitting patches
Patches can be submitted using the Merge-Request link of our gitlab.
## Mailinglist
https://lists.ffnw.de/mailman/listinfo/netmon-dev
# License
See [License](LICENSE.txt)
{
"name": "netmon-server/places",
"description": "This project holds the Places module for the Netmon API-Server. It handles geographical coordinates (latitude, longitude, elevation) and administrative locations (contact information of a roof or a building in example).",
"license": "MIT",
"keywords": ["laravel", "freifunk", "netmon"],
"autoload": {
"psr-4": {
"Netmon\\Places\\": "src/",
"Netmon\\Places\\Http\\Controllers\\": "src/Http/Controllers/",
"Netmon\\Places\\Models\\": "src/Models/",
"Netmon\\Places\\Policies\\": "src/Policies/",
"Netmon\\Places\\Providers\\": "src/Providers/",
"Netmon\\Places\\Serializers\\": "src/Serializers/",
"Netmon\\Places\\Tests\\": "tests/"
}
},
"require": {
"illuminate/support": "~5"
}
}
# Creating a release
1. Use [semantic versioning](http://semver.org/) for release versions
1. Adjust 3rd party depencies in [composer.json](composer.json)
1. Update 3rd party depencies using `composer update`
1. Commit composer update using `git commit -sam`
1. Create a signed tag and add a release description to the tag using `git tag -a -s <VERSION> <COMMIT-ID>`
1. Push tags using `git push --tags`
# Technology stack
## NetJSON
This module uses the http://netjson.org specification as inspiration for
resources and their attributes.
## Unittesting
From within a working Netmon server installation run:
```
cd vendor/netmon-server/devices
phpunit --bootstrap ../../../bootstrap/autoload.php
```
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_ENV" value="testing"/>
<!--
Any further environment configuration
is done in .env.testing file
-->
</php>
</phpunit>
<?php
namespace Netmon\Places\Http\Controllers;
use Netmon\JsonApi\Http\Controllers\DefaultResourceController;
class CoordinatesController extends DefaultResourceController
{
public function model() {
return \Netmon\Places\Models\Coordinate::class;
}
public function serializer() {
return \Netmon\Places\Serializers\CoordinateSerializer::class;
}
public function resource() {
return "coordinates";
}
}
<?php
Route::group([
'namespace' => '\Netmon\Places\Http\Controllers',
'middleware' => 'cors'], function()
{
/**
* Routes using JWT auth
*/
Route::group(['middleware' => ['auth.jwt']], function () {
Route::resource('coordinates', CoordinatesController::class, ['only' => [
'index', 'show', 'store', 'update', 'destroy'
]]);
});
});
?>
<?php
namespace Netmon\Places\Models;
use Netmon\Server\App\Models\BaseModel;
use Netmon\Server\App\Traits\UuidForKeyTrait;
class Coordinate extends BaseModel
{
use UuidForKeyTrait;
/**
* Bootstrap any application services.
*/
public static function boot()
{
parent::boot();
//Register validation service
//on saving event
self::saving(
function ($model) {
return $model->validate();
}
);
self::creating(
function ($model) {
// assign currently authenticated user as creator
$user = \Auth::user();
if(!empty($user->id)) {
$model->creator_id = $user->id;
}
}
);
}
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'coordinates';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
// meta
'creator_id',
// general
'latitude',
'longitude',
'elevation',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [];
/**
* Define default values of model. Example:
* @var array
*/
protected $attributes = [];
/**
* Holds the validation errors if some
* @var unknown
*/
protected $validationErrors = false;
/**
* Holds the validation rules
* @var unknown
*/
public $validationRules = [
'creator_id' => 'nullable|exists:users,id',
'latitude' => [
'required',
'regex:/^(\-?\d+(\.\d+)?)\.\s*(\-?\d+(\.\d+)?)$/'
],
'longitude' => [
'required',
'regex:/^(\-?\d+(\.\d+)?)\.\s*(\-?\d+(\.\d+)?)$/'
],
'elevation' => 'nullable|integer',
];
/**
* n:1 relation to users
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function creator() {
return $this->belongsTo(\Netmon\Server\App\Models\User::class);
}
}
<?php
namespace Netmon\Places;
use Illuminate\Support\ServiceProvider;
class ModuleServiceProvider extends ServiceProvider
{
public function register()
{
//register all the service provider this module needs
$this->app->register(\Netmon\Places\Providers\AuthServiceProvider::class);
$this->app->register(\Netmon\Places\Providers\EventServiceProvider::class);
$this->app->register(\Netmon\Places\Providers\RelationsServiceProvider::class);
}
public function boot()
{
require __DIR__ . '/Http/routes.php';
//register database migrations
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
}
}
?>
<?php
namespace Netmon\Places\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
use Netmon\Server\App\Policies\BasePolicy;
use Netmon\Places\Models\Coordinate;
use Netmon\Server\App\Models\User;
class CoordinatePolicy extends BasePolicy
{
use HandlesAuthorization;
public function index(User $authUser) {
//everyone is allowed to list coordinates
return true;
}
public function store(User $authUser, Coordinate $coordinate = null) {
return $this->checkPermissions($authUser, 'store', 'coordinate');
}
public function show(User $authUser, Coordinate $coordinate) {
//everyone is allowed to show coordinate
return true;
}
public function update(User $authUser, Coordinate $coordinate) {
return $this->checkPermissions($authUser, 'update', 'coordinate', $coordinate);
}
public function destroy(User $authUser, Coordinate $coordinate) {
return $this->checkPermissions($authUser, 'destroy', 'coordinate', $coordinate);
}
}
<?php
namespace Netmon\Places\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
\Netmon\Places\Models\Coordinate::class => \Netmon\Places\Policies\CoordinatePolicy::class,
];
/**
* Register any application authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
}
}
<?php
namespace Netmon\Places\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Netmon\Server\App\Models\Permission;
use Netmon\Places\Models\Coordinate;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
];
/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
\Event::listen('api.coordinate.created', function (Coordinate $coordinate) {
$user = \Auth::user();
Permission::create([
'user_id' => $user->id,
'action_id' => 'show',
'resource_id' => 'coordinate',
'object_key' => $coordinate->id
]);
Permission::create([
'user_id' => $user->id,
'action_id' => 'update',
'resource_id' => 'coordinate',
'object_key' => $coordinate->id
]);
Permission::create([
'user_id' => $user->id,
'action_id' => 'destroy',
'resource_id' => 'coordinate',
'object_key' => $coordinate->id
]);
});
}
}
<?php
namespace Netmon\Places\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class RelationsServiceProvider extends ServiceProvider
{
/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
config([
'runtimeRelations.models.'.\Netmon\Server\App\Models\User::class => [
'createdCoordinates' => [
'type' => 'hasMany',
'model' => \Netmon\Places\Models\Coordinate::class,
'foreignKey' => 'creator_id',
'localKey' => null
]
]
]);
config([
'runtimeRelations.serializers.'.\Netmon\Server\App\Serializers\UserSerializer::class => [
'createdCoordinates' => [
'type' => 'hasMany',
'serializer' => \Netmon\Paces\Serializers\CoortinateSerializer::class
]
]
]);
parent::boot();
}
}
<?php
namespace Netmon\Places\Serializers;
use Gate;
use Netmon\JsonApi\Serializers\BasicSerializer;
use Netmon\Places\Models\Coordinate;
class CoordinateSerializer extends BasicSerializer
{
protected $type = 'coordinates';
public function getAttributes($model, array $fields = null)
{
if (! ($model instanceof Coordinate)) {
throw new \InvalidArgumentException(
get_class($this).' can only serialize instances of '.Place::class
);
}
// set up attributes
$attributes = $model->getAttributes();
$attributes['created_at'] = $this->formatDate($model->created_at);
$attributes['updated_at'] = $this->formatDate($model->updated_at);
return $attributes;
}
public function getLinks($model) {
//links to always include in the resource
$links = [
'self' => config('app.url')."/coordinates/{$model->id}",
];
//links to include based permissions
if(Gate::allows('show', $model))
$links['read'] = config('app.url')."/coordinates/{$model->id}";
if(Gate::allows('update', $model))
$links['update'] = config('app.url')."/coordinates/{$model->id}";
if(Gate::allows('destroy', $model))
$links['delete'] = config('app.url')."/coordinates/{$model->id}";
return $links;
}
/**
* @return \Tobscure\JsonApi\Relationship
*/
protected function creator($model)
{
return $this->hasOne($model, \Netmon\Server\App\Serializers\UserSerializer::class);
}
}
?>
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePlaces extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('coordinates', function (Blueprint $table) {
//meta
$table->uuid('id')->primary();
$table->uuid('creator_id')->nullabe();
$table->foreign('creator_id')
->references('id')
->on('users')
->onDelete('cascade');
//general
$table->float('latitude', 10, 6);
$table->float('longitude', 10, 6);
$table->integer('elevation')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('coordinates');
}
}
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Netmon\Server\App\Models\Role;
use Netmon\Server\App\Models\Permission;
use Netmon\Server\App\Models\Config;
class CreatePlacePermissions extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$userRoleId = Config::where(
'key',
'serverUserRoleId'
)->firstOrFail()->value;
Permission::create([
'role_id' => $userRoleId,
'action_id' => 'store',
'resource_id' => 'coordinate',
]);
//admin permissions
$adminRoleId = Config::where(
'key',
'serverAdminRoleId'
)->firstOrFail()->value;
Permission::create([
'role_id' => $adminRoleId,
'action_id' => 'index',
'resource_id' => 'coordinate',
]);
Permission::create([
'role_id' => $adminRoleId,
'action_id' => 'show',
'resource_id' => 'coordinate',
]);
Permission::create([
'role_id' => $adminRoleId,
'action_id' => 'store',
'resource_id' => 'coordinate',
]);
Permission::create([
'role_id' => $adminRoleId,
'action_id' => 'update',
'resource_id' => 'coordinate',
]);
Permission::create([
'role_id' => $adminRoleId,
'action_id' => 'destroy',
'resource_id' => 'coordinate',
]);
}