Skip to content

Commit

Permalink
Release 1.2.0 (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
NuwanJ authored Sep 21, 2024
1 parent bf31809 commit 281203d
Show file tree
Hide file tree
Showing 31 changed files with 434 additions and 84 deletions.
4 changes: 2 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ APP_URL=http://localhost
SEED_ADMIN_EMAIL=[email protected]
SEED_ADMIN_PASSWORD=admin_user

SEED_NEWS_EDITOR_EMAIL="[email protected]"
SEED_NEWS_EDITOR_EMAIL="user+[email protected]"
SEED_NEWS_EDITOR_PASSWORD="news_editor"

SEED_EVENT_EDITOR_EMAIL="[email protected]"
SEED_EVENT_EDITOR_EMAIL="user+[email protected]"
SEED_EVENT_EDITOR_PASSWORD="events_editor"

SEED_USER_EMAIL=[email protected]
Expand Down
File renamed without changes.
31 changes: 31 additions & 0 deletions .github/workflows/laravel_push.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Laravel Push Test

on: [push]

jobs:
laravel-tests:
runs-on: ubuntu-latest

steps:
- uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e
with:
php-version: '8.0'
- uses: actions/checkout@v2
- name: Copy .env
run: php -r "file_exists('.env') || copy('.env.example', '.env');"
- name: Install Dependencies
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
- name: Generate key
run: php artisan key:generate
- name: Directory Permissions
run: chmod -R 777 storage bootstrap/cache
- name: Create Database
run: |
mkdir -p database
touch database/database.sqlite
- name: Execute tests (Unit and Feature tests) via PHPUnit
env:
DB_CONNECTION: sqlite
DB_DATABASE: database/database.sqlite
run: |
php artisan test -p --colors --debug
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use LangleyFoxall\LaravelNISTPasswordRules\PasswordRules;
use App\Rules\ValidateAsInternalEmail;

/**
* Class RegisterController.
Expand Down Expand Up @@ -74,7 +75,7 @@ protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:100'],
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')],
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users'), new ValidateAsInternalEmail()],
'password' => array_merge(['max:100'], PasswordRules::register($data['email'] ?? null)),
'terms' => ['required', 'in:1'],
'g-recaptcha-response' => ['required_if:captcha_status,true', new Captcha],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use App\Domains\Auth\Events\User\UserLoggedIn;
use App\Domains\Auth\Services\UserService;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Validator;
use App\Rules\ValidateAsInternalEmail;

/**
* Class SocialController.
Expand All @@ -30,7 +32,30 @@ public function redirect($provider)
*/
public function callback($provider, UserService $userService)
{
$user = $userService->registerProvider(Socialite::driver($provider)->user(), $provider);
// Validate for internal user
$info = Socialite::driver($provider)->user();
$validator = Validator::make(
['email' => $info->email, 'name' => $info->name],
['email' => ['required', 'email', new ValidateAsInternalEmail()], 'name' => ['required']]
);

if ($validator->fails()) {
$errorMessage = "";
$errors = $validator->errors();

foreach ($errors->messages() as $key => $messages) {
if (is_array($messages)) {
foreach ($messages as $message) {
$errorMessage .= $message . ' ';
}
} else {
$errorMessage .= $messages . ' ';
}
}
return redirect()->route('frontend.auth.login')->withFlashDanger(trim($errorMessage));
}

$user = $userService->registerProvider($info, $provider);

if (!$user->isActive()) {
auth()->logout();
Expand All @@ -43,4 +68,4 @@ public function callback($provider, UserService $userService)

return redirect()->route(homeRoute());
}
}
}
10 changes: 8 additions & 2 deletions app/Domains/Event/Models/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

namespace App\Domains\Event\Models;

use App\Domains\Event\Models\Traits\Scope\EventScope;
use App\Domains\Auth\Models\User;
use Database\Factories\EventFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use App\Domains\Event\Models\Traits\Scope\EventScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;

/**
* Class News.
Expand Down Expand Up @@ -53,6 +54,11 @@ public function thumbURL()
else return config('constants.frontend.dummy_thumb');
}

public function user()
{
return $this->belongsTo(User::class, 'created_by');
}

/**
* Create a new factory instance for the model.
*
Expand Down
11 changes: 9 additions & 2 deletions app/Domains/News/Models/News.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

namespace App\Domains\News\Models;

use App\Domains\News\Models\Traits\Scope\NewsScope;
use App\Domains\Auth\Models\User;
use Database\Factories\NewsFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use App\Domains\News\Models\Traits\Scope\NewsScope;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;

/**
* Class News.
Expand Down Expand Up @@ -47,6 +49,11 @@ public function thumbURL()
else return config('constants.frontend.dummy_thumb');
}

public function user()
{
return $this->belongsTo(User::class, 'created_by');
}

/**
* Create a new factory instance for the model.
*
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Controllers/Backend/EventController.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public function update(Request $request, Event $event)
$data = request()->validate([
'title' => ['required'],
'url' =>
['required', Rule::unique('news')->ignore($event->id)],
['required', Rule::unique('events')->ignore($event->id)],
'published_at' => 'required|date_format:Y-m-d',
'description' => 'string',
'enabled' => 'nullable',
Expand Down
4 changes: 2 additions & 2 deletions app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class Kernel extends HttpKernel
'is_admin' => \App\Domains\Auth\Http\Middleware\AdminCheck::class,
'is_super_admin' => \App\Domains\Auth\Http\Middleware\SuperAdminCheck::class,
'is_user' => \App\Domains\Auth\Http\Middleware\UserCheck::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'password.confirm' => \App\Http\Middleware\CustomRequirePassword::class, // \Illuminate\Auth\Middleware\RequirePassword::class,
'password.expires' => \App\Domains\Auth\Http\Middleware\PasswordExpires::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
Expand All @@ -105,4 +105,4 @@ class Kernel extends HttpKernel
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
}
2 changes: 1 addition & 1 deletion app/Http/Livewire/Backend/NewsTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function columns(): array
->format(function (News $news) {
return view('backend.news.enabled-toggle', ['news' => $news]);
}),
Column::make("Author")
Column::make("Author","user.name")
->sortable()
->searchable(),
Column::make("Published at", "published_at")
Expand Down
39 changes: 39 additions & 0 deletions app/Http/Middleware/CustomRequirePassword.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\RequirePassword;

class CustomRequirePassword extends RequirePassword
{


/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $redirectToRoute
* @return mixed
*/
public function handle($request, Closure $next, $redirectToRoute = null)
{
// Skip password confirmation in the test environment
if (app()->environment('testing')) {
return $next($request);
}

// Should ask only if user has password = not signed in with providers
$hasPassword = $this->hasPassword($request);
if ($hasPassword) {
return parent::handle($request, $next, $redirectToRoute);
}
return $next($request);
}

protected function hasPassword($request)
{
return (!in_array($request->user()->provider, ['google']));
}
}
1 change: 1 addition & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,6 @@ public function boot()
{
Paginator::useBootstrap();
Schema::defaultStringLength(191);
ini_set('max_execution_time', 120);
}
}
44 changes: 44 additions & 0 deletions app/Rules/ValidateAsInternalEmail.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\Services\DepartmentDataService;

class ValidateAsInternalEmail implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}

/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
// Skip email validator in unit testing, to save time
if (app()->environment() == 'testing') return true;
$api = new DepartmentDataService();
return $api->isInternalEmail($value);
}

/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return "Only Department of Computer Engineering students/staff are allowed to register by themselves.";
}
}
64 changes: 64 additions & 0 deletions app/Services/DepartmentDataService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class DepartmentDataService
{
public function isInternalEmail($userEmail)
{
$emails = Cache::remember(
'dept_service_user_emails',
config('constants.department_data.cache_duration'),
function () {

// Students
$students = $this->getData('/people/v1/students/all/');
$student_emails = collect($students)->map(function ($user) {
$faculty_name = $user['emails']['faculty']['name'];
$faculty_domain = $user['emails']['faculty']['domain'];

$personal_name = $user['emails']['faculty']['name'];
$personal_domain = $user['emails']['faculty']['domain'];

if ($faculty_domain == 'eng.pdn.ac.lk' && $faculty_name != '' && $faculty_domain != '') {
// Faculty Email
return "$faculty_name@$faculty_domain";
} else if ($personal_domain == 'eng.pdn.ac.lk') {
// Personal Email
return "$personal_name@$personal_domain";
}
return null;
});

// Staff
$staff = $this->getData('/people/v1/staff/all/');
$staff_emails = collect($staff)->map(function ($user) {
return $user['email'];
});

return $student_emails->union($staff_emails)->filter()->values()->toArray();
}
);
return in_array($userEmail, $emails);
}

private function getData($endpoint)
{
$url = config('constants.department_data.base_url') . $endpoint;
$response = Http::get($url);

if ($response->successful()) {
return $response->json();
} else {
$statusCode = $response->status();
$errorMessage = $response->body();

Log::error('Error in getData: ' . $errorMessage);
return [];
}
}
}
2 changes: 1 addition & 1 deletion config/boilerplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,4 @@
|
*/
'testing' => env('APP_TESTING', false),
];
];
8 changes: 6 additions & 2 deletions config/constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,9 @@
'frontend' => [
'dummy_thumb' => '/dummy/item_thumbnail.jpg',
],
'backend' => []
];
'backend' => [],
'department_data' => [
'base_url' => 'https://api.ce.pdn.ac.lk',
'cache_duration' => 43200 // 6 hours
]
];
Loading

0 comments on commit 281203d

Please sign in to comment.