Initial upload of the control panel

This commit is contained in:
Pinga 2023-08-07 13:14:05 +03:00
parent f21bd93fbc
commit 7eab26586c
791 changed files with 312718 additions and 0 deletions

306
cp/app/Auth/Auth.php Normal file
View file

@ -0,0 +1,306 @@
<?php
namespace App\Auth;
use App\Lib\Mail;
use Pinga\Auth\ConfirmationRequestNotFound;
use Pinga\Auth\EmailNotVerifiedException;
use Pinga\Auth\InvalidEmailException;
use Pinga\Auth\InvalidPasswordException;
use Pinga\Auth\InvalidSelectorTokenPairException;
use Pinga\Auth\NotLoggedInException;
use Pinga\Auth\ResetDisabledException;
use Pinga\Auth\TokenExpiredException;
use Pinga\Auth\TooManyRequestsException;
use Pinga\Auth\UserAlreadyExistsException;
/**
* Auth
*
* @author Hezekiah O. <support@hezecom.com>
*/
class Auth
{
static protected $auth;
/**
* Auth constructor.
*/
public function __construct()
{
self::$auth = auth();
}
/**
* @param $email
* @param $username
* @param $password
* @param array $info
* @return int
* @throws \Pinga\Auth\AuthError
*/
public static function create($email, $username, $password, $info=[]){
$auth = self::$auth;
try {
$userId = $auth->register($email, $username, $password, function ($selector, $token) use ($email, $username) {
$link = url('verify.email',[],['selector'=>urlencode($selector),'token'=>urlencode($token)]);
$message = file_get_contents(__DIR__.'/../../resources/views/auth/mail/confirm-email.html');
$message = str_replace(['{link}','{app_name}'],[$link,envi('APP_NAME')],$message);
$subject = 'Email Verification';
$from = ['email'=>envi('MAIL_FROM_ADDRESS'), 'name'=>envi('APP_NAME')];
$to = ['email'=>$email, 'name'=>$username];
// send message
Mail::send($subject, $message, $from, $to);
});
//$auth->admin()->addRoleForUserById($userId, Role::ADMIN);
return $userId;
}
catch (InvalidEmailException $e) {
redirect()->route('register')->with('error','Invalid email address');
}
catch (InvalidPasswordException $e) {
redirect()->route('register')->with('error','Invalid password');
}
catch (UserAlreadyExistsException $e) {
redirect()->route('register')->with('error','User already exists test');
}
catch (TooManyRequestsException $e) {
redirect()->route('register')->with('error','Too many requests, try again later');
}
}
/**
* @param $selector
* @param $token
* @throws \Pinga\Auth\AuthError
*/
public static function verifyEmail($selector, $token){
$auth = self::$auth;
try {
$auth->confirmEmail($selector, $token);
//echo 'Email address has been verified';
redirect()->route('login')->with('success','Email address has been verified');
}
catch (InvalidSelectorTokenPairException $e) {
redirect()->route('login')->with('error','Invalid token');
}
catch (TokenExpiredException $e) {
redirect()->route('login')->with('error','Token expired');
}
catch (UserAlreadyExistsException $e) {
redirect()->route('login')->with('error','Email address already exists');
}
catch (TooManyRequestsException $e) {
redirect()->route('login')->with('error','Too many requests, try again later.');
}
}
/**
* Re-sending confirmation requests
* @param $email
*/
public static function ResendVerification($email){
$auth = self::$auth;
try {
$auth->resendConfirmationForEmail($email, function ($selector, $token) use ($email) {
$link = url('verify.email',[],['selector'=>urlencode($selector),'token'=>urlencode($token)]);
$message = file_get_contents(__DIR__.'/../../resources/views/auth/mail/confirm-email.html');
$message = str_replace(['{link}','{app_name}'],[$link,envi('APP_NAME')],$message);
$subject = 'Email Verification';
$from = ['email'=>envi('MAIL_FROM_ADDRESS'), 'name'=>envi('MAIL_FROM_NAME')];
$to = ['email'=>$email, 'name'=>''];
// send message
Mail::send($subject, $message, $from, $to);
});
redirect()->route('login')->with('success','We have sent you another email. Please follow the link to verify your email.');
}
catch (ConfirmationRequestNotFound $e) {
redirect()->route('login')->with('error','No earlier request found that could be re-sent.');
}
catch (TooManyRequestsException $e) {
redirect()->route('login')->with('error','Too many requests, try again later');
}
}
/**
* @param $email
* @param $password
* @param null $remember
* @throws \Pinga\Auth\AttemptCancelledException
* @throws \Pinga\Auth\AuthError
*/
public static function login($email, $password, $remember=null){
$auth = self::$auth;
try {
if ($remember !='') {
// keep logged in for one year
$rememberDuration = (int) (60 * 60 * 24 * 365.25);
}
else {
// do not keep logged in after session ends
$rememberDuration = null;
}
$auth->login($email, $password,$rememberDuration);
return true;
}
catch (InvalidEmailException $e) {
redirect()->route('login')->with('error','Wrong email address');
}
catch (InvalidPasswordException $e) {
redirect()->route('login')->with('error','Wrong password');
}
catch (EmailNotVerifiedException $e) {
redirect()->route('login')->with('error','Email not verified');
die('Email not verified');
}
catch (TooManyRequestsException $e) {
redirect()->route('login')->with('error','Too many requests');
}
}
/**
* Reset Password 1 of 3
* @param $email
* @throws \Pinga\Auth\AuthError
*/
public static function forgotPassword($email){
$auth = self::$auth;
try {
$auth->forgotPassword($email, function ($selector, $token) use ($email) {
$link = url('reset.password',[],['selector'=>urlencode($selector),'token'=>urlencode($token)]);
$message = file_get_contents(__DIR__.'/../../resources/views/auth/mail/reset-password.html');
$message = str_replace(['{link}','{app_name}'],[$link,envi('APP_NAME')],$message);
$subject = 'Reset Password';
$from = ['email'=>envi('MAIL_FROM_ADDRESS'), 'name'=>envi('MAIL_FROM_NAME')];
$to = ['email'=>$email, 'name'=>''];
// send message
Mail::send($subject, $message, $from, $to);
});
redirect()->route('forgot.password')->with('success','A password reset link has been sent to your email.');
}
catch (InvalidEmailException $e) {
redirect()->route('forgot.password')->with('error','Invalid email address');
}
catch (EmailNotVerifiedException $e) {
redirect()->route('forgot.password')->with('error','Email not verified');
}
catch (ResetDisabledException $e) {
redirect()->route('forgot.password')->with('error','Password reset is disabled');
}
catch (TooManyRequestsException $e) {
redirect()->route('forgot.password')->with('error','Too many requests, try again later');
}
}
/**
* Reset Password 2 of 3
* @param $selector
* @param $token
* @throws \Pinga\Auth\AuthError
*/
public static function resetPasswordVerify($selector, $token){
$auth = self::$auth;
try {
$auth->canResetPasswordOrThrow($selector, $token);
redirect()->route('update.password',[],['selector'=>urlencode($selector),'token'=>urlencode($token)]);
}
catch (InvalidSelectorTokenPairException $e) {
redirect()->route('forgot.password')->with('error','Invalid token');
}
catch (TokenExpiredException $e) {
redirect()->route('forgot.password')->with('error','Token expired');
}
catch (ResetDisabledException $e) {
redirect()->route('forgot.password')->with('error','Password reset is disabled');
}
catch (TooManyRequestsException $e) {
redirect()->route('forgot.password')->with('error','Too many requests, try again later');
}
}
/**
* Reset Password 3 of 3
* @param $selector
* @param $token
* @param $password
* @throws \Pinga\Auth\AuthError
*/
public static function resetPasswordUpdate($selector, $token, $password){
$auth = self::$auth;
try {
$auth->resetPassword($selector, $token, $password);
redirect()->route('login')->with('success','Password has been reset');
}
catch (InvalidSelectorTokenPairException $e) {
redirect()->route('update.password',[],['selector'=>urlencode($selector),'token'=>urlencode($token)])->with('error','Invalid token');
}
catch (TokenExpiredException $e) {
redirect()->route('update.password',[],['selector'=>urlencode($selector),'token'=>urlencode($token)])->with('error','Token expired');
}
catch (ResetDisabledException $e) {
redirect()->route('update.password',[],['selector'=>urlencode($selector),'token'=>urlencode($token)])->with('error','Password reset is disabled');
}
catch (InvalidPasswordException $e) {
redirect()->route('update.password',[],['selector'=>urlencode($selector),'token'=>urlencode($token)])->with('error','Invalid password');
}
catch (TooManyRequestsException $e) {
redirect()->route('login')->with('error','Too many requests, try again later');
}
}
/**
* Changing the current users password when logged in only
* @param $oldPassword
* @param $newPassword
* @throws \Pinga\Auth\AuthError
*/
public static function changeCurrentPassword($oldPassword, $newPassword){
$auth = self::$auth;
try {
$auth->changePassword($oldPassword, $newPassword);
redirect()->route('profile')->with('success','Password has been changed');
}
catch (NotLoggedInException $e) {
redirect()->route('profile')->with('error','You are not logged in');
}
catch (InvalidPasswordException $e) {
redirect()->route('profile')->with('error','Your old password do not match');
}
catch (TooManyRequestsException $e) {
redirect()->route('profile')->with('error','Too many requests, try again later');
}
}
/**
* @throws \Pinga\Auth\AuthError
*/
public static function logout(){
return self::$auth->logOut();
}
/**
* @return bool
*/
public function isLogin(){
if (self::$auth->isLoggedIn()) {
return true;
}
else {
return false;
}
}
/**
* @return array
*/
public function user(){
$auth = self::$auth;
$info = [
'id' => $auth->getUserId(),
'email' => $auth->getEmail(),
'username' => $auth->getUsername(),
'ip' => $auth->getIpAddress()
];
return $info;
}
}

View file

@ -0,0 +1,117 @@
<?php
namespace App\Controllers\Auth;
use App\Auth\Auth;
use App\Controllers\Controller;
use Respect\Validation\Validator as v;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* AuthController
*
* @author Hezekiah O. <support@hezecom.com>
*/
class AuthController extends Controller
{
/**
* @param Request $request
* @param Response $response
* @return mixed
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function createRegister(Request $request, Response $response){
return view($response,'auth/register.twig');
}
/**
* @param Request $request
* @param Response $response
* @return Response
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
* @throws \Pinga\Auth\AuthError
*/
public function register(Request $request, Response $response){
$validation = $this->validator->validate($request, [
'email' => v::noWhitespace()->notEmpty()->email(),
'username' => v::noWhitespace()->notEmpty()->alnum(),
'password' => v::notEmpty()->stringType()->length(8),
]);
if ($validation->failed()) {
redirect()->route('register');
//or
//return $response->withHeader('Location', route('register'));
}
$data = $request->getParsedBody();
$auth =Auth::create($data['email'],$data['password'],$data['username']);
if($auth) {
$msg = '<a href="'.route('verify.email.resend',[],['email'=>$data['email']]).'">Resend email</a>';
flash('success', 'We have send you a verification link to '.$data['email'].' <br>'.$msg);
return $response->withHeader('Location', route('login'));
}
}
/**
* @param Request $request
* @param Response $response
*/
public function verifyEmailResend(Request $request, Response $response){
$data = $request->getQueryParams();
Auth::ResendVerification($data['email']);
}
/**
* @param Request $request
* @param Response $response
* @throws \Pinga\Auth\AuthError
*/
public function verifyEmail(Request $request, Response $response){
//confirm email
$data = $request->getQueryParams();
Auth::verifyEmail($data['selector'], $data['token']);
}
/**
* @param Request $request
* @param Response $response
* @return mixed
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function createLogin(Request $request, Response $response){
return view($response,'auth/login.twig');
}
/**
* @param Request $request
* @param Response $response
* @throws \Pinga\Auth\AttemptCancelledException
* @throws \Pinga\Auth\AuthError
*/
public function login(Request $request, Response $response){
$data = $request->getParsedBody();
if(isset($data['remember'])){
$remember = $data['remember'];
}else{
$remember = null;
}
$login = Auth::login($data['email'], $data['password'], $remember);
if($login===true)
redirect()->route('home');
}
/**
* @throws \Pinga\Auth\AuthError
*/
public function logout()
{
Auth::logout();
redirect()->route('login');
}
}

View file

@ -0,0 +1,101 @@
<?php
namespace App\Controllers\Auth;
use App\Auth\Auth;
use App\Controllers\Controller;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Respect\Validation\Validator as v;
/**
* PasswordController
*
* @author Hezekiah O. <support@hezecom.com>
*/
class PasswordController extends Controller
{
/**
* @param Request $request
* @param Response $response
* @return mixed
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function createForgotPassword(Request $request, Response $response){
return view($response,'auth/password/forgot-password.twig');
}
/**
* @param Request $request
* @param Response $response
* @throws \Pinga\Auth\AuthError
*/
public function forgotPassword(Request $request, Response $response){
$data = $request->getParsedBody();
Auth::forgotPassword($data['email']);
}
/**
* @param Request $request
* @param Response $response
* @throws \Pinga\Auth\AuthError
*/
public function resetPassword(Request $request, Response $response){
$data = $request->getQueryParams();
Auth::resetPasswordVerify($data['selector'], $data['token']);
}
/**
* @param Request $request
* @param Response $response
* @return mixed
* @throws \DI\DependencyException
* @throws \DI\NotFoundException
*/
public function createUpdatePassword(Request $request, Response $response){
$data = $request->getQueryParams();
$selector = $data['selector'];
$token = $data['token'];
return view($response,'auth/password/update-password.twig', compact('selector','token'));
}
/**
* @param Request $request
* @param Response $response
* @throws \Pinga\Auth\AuthError
*/
public function updatePassword(Request $request, Response $response){
$data = $request->getParsedBody();
$validation = $this->validator->validate($request, [
'password' => v::notEmpty()->stringType()->length(8),
'password2' => v::notEmpty(),
]);
if ($validation->failed()) {
redirect()->route('update.password',[],['selector'=>urlencode($data['selector']),'token'=>urlencode($data['token'])]);
}
elseif (!v::equals($data['password'])->validate($data['password2'])) {
redirect()->route('update.password',[],['selector'=>urlencode($data['selector']),'token'=>urlencode($data['token'])])->with('error','The password do not match.');
}
Auth::resetPasswordUpdate($data['selector'], $data['token'], $data['password']);
}
/**
* @param Request $request
* @param Response $response
* @throws \Pinga\Auth\AuthError
*/
public function changePassword(Request $request, Response $response){
$data = $request->getParsedBody();
$validation = $this->validator->validate($request, [
'old_password' => v::notEmpty(),
'new_password' => v::notEmpty()->stringType()->length(8),
]);
if ($validation->failed()) {
redirect()->route('profile');
}
Auth::changeCurrentPassword($data['old_password'], $data['new_password']);
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace App\Controllers;
use DI\Container;
/**
* Controller
*
* @author Hezekiah O. <support@hezecom.com>
*/
class Controller
{
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function __get($property)
{
if ($this->container->get($property)) {
return $this->container->get($property);
}
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace App\Controllers;
use App\Models\User;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Container\ContainerInterface;
class HomeController extends Controller
{
public function index(Request $request, Response $response)
{
return view($response,'index.twig');
}
public function dashboard(Request $request, Response $response)
{
$userModel = new User($this->container->get('db'));
$users = $userModel->getAllUsers();
return view($response,'admin/dashboard/index.twig', compact('users'));
}
public function mode(Request $request, Response $response)
{
if ($_SESSION['_screen_mode'] == 'dark') {
$_SESSION['_screen_mode'] = 'light';
} else {
$_SESSION['_screen_mode'] = 'dark';
}
$referer = $request->getHeaderLine('Referer');
if (!empty($referer)) {
return $response->withHeader('Location', $referer)->withStatus(302);
}
return $response->withHeader('Location', '/dashboard')->withStatus(302);
}
public function avatar(Request $request, Response $response)
{
$avatar = new \LasseRafn\InitialAvatarGenerator\InitialAvatar();
$stream = $avatar->name($_SESSION['auth_username'])->length(2)->fontSize(0.5)->size(96)->background('#206bc4')->color('#fff')->generate()->stream('png', 100);
$psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory();
$psrResponse = $psr17Factory->createResponse(200)->withBody($stream);
return $psrResponse;
}
}

View file

@ -0,0 +1,112 @@
<?php
namespace App\Controllers;
use App\Models\User;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Container\ContainerInterface;
class ProfileController extends Controller
{
public function profile(Request $request, Response $response)
{
$username = $_SESSION['auth_username'];
$email = $_SESSION['auth_email'];
$status = $_SESSION['auth_status'];
if ($status == 0) {
$status = "Confirmed";
} else {
$status = "Unknown";
}
$roles = $_SESSION['auth_roles'];
if ($roles == 0) {
$role = "Admin";
} else {
$role = "Unknown";
}
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role]);
}
public function notifications(Request $request, Response $response)
{
$username = $_SESSION['auth_username'];
$email = $_SESSION['auth_email'];
$status = $_SESSION['auth_status'];
if ($status == 0) {
$status = "Confirmed";
} else {
$status = "Unknown";
}
$roles = $_SESSION['auth_roles'];
if ($roles == 0) {
$role = "Admin";
} else {
$role = "Unknown";
}
return view($response,'admin/profile/notifications.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role]);
}
public function security(Request $request, Response $response)
{
$username = $_SESSION['auth_username'];
$email = $_SESSION['auth_email'];
$status = $_SESSION['auth_status'];
if ($status == 0) {
$status = "Confirmed";
} else {
$status = "Unknown";
}
$roles = $_SESSION['auth_roles'];
if ($roles == 0) {
$role = "Admin";
} else {
$role = "Unknown";
}
return view($response,'admin/profile/security.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role]);
}
public function plans(Request $request, Response $response)
{
$username = $_SESSION['auth_username'];
$email = $_SESSION['auth_email'];
$status = $_SESSION['auth_status'];
if ($status == 0) {
$status = "Confirmed";
} else {
$status = "Unknown";
}
$roles = $_SESSION['auth_roles'];
if ($roles == 0) {
$role = "Admin";
} else {
$role = "Unknown";
}
return view($response,'admin/profile/plans.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role]);
}
public function invoices(Request $request, Response $response)
{
$username = $_SESSION['auth_username'];
$email = $_SESSION['auth_email'];
$status = $_SESSION['auth_status'];
if ($status == 0) {
$status = "Confirmed";
} else {
$status = "Unknown";
}
$roles = $_SESSION['auth_roles'];
if ($roles == 0) {
$role = "Admin";
} else {
$role = "Unknown";
}
return view($response,'admin/profile/invoices.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role]);
}
}

18
cp/app/Lib/Config.php Normal file
View file

@ -0,0 +1,18 @@
<?php namespace App\Lib;
/**
* Config
*
* @author Hezekiah O. <support@hezecom.com>
*/
class Config
{
private static $config;
public static function get($key, $default = null)
{
if (is_null(self::$config)) {
self::$config = require_once(__DIR__ . '/../../config/app.php');
}
return !empty(self::$config[$key]) ? self::$config[$key] : $default;
}
}

79
cp/app/Lib/Logger.php Normal file
View file

@ -0,0 +1,79 @@
<?php namespace App\Lib;
use Monolog\ErrorHandler;
use Monolog\Handler\StreamHandler;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
/**
* Logger
*
* @author Hezekiah O. <support@hezecom.com>
*/
class Logger extends \Monolog\Logger
{
private static $loggers = [];
/**
* Logger constructor.
* @param string $key
* @param null $config
* @throws \Exception
*/
public function __construct($key = "app", $config = null)
{
parent::__construct($key);
if (empty($config)) {
$LOG_PATH = '/tmp/slim';
$config = [
'logFile' => "{$LOG_PATH}/{$key}.log",
'logLevel' => \Monolog\Logger::DEBUG
];
}
$this->pushHandler(new StreamHandler($config['logFile'], $config['logLevel']));
}
/**
* @param string $key
* @param null $config
* @return mixed
*/
public static function getInstance($key = "app", $config = null)
{
if (empty(self::$loggers[$key])) {
self::$loggers[$key] = new Logger($key, $config);
}
return self::$loggers[$key];
}
/**
* Output error bate on environment
*/
public static function systemLogs($enable = true)
{
$LOG_PATH = '/tmp/slim';
$appEnv = envi('APP_ENV') ?? 'local';
if($enable) {
// output pretty html error
self::htmlError();
}else {
// Error Log to file
self::$loggers['error'] = new Logger('errors');
self::$loggers['error']->pushHandler(new StreamHandler("{$LOG_PATH}/errors.log"));
ErrorHandler::register(self::$loggers['error']);
}
}
/**
* Display pretty html formatted errors during development
*/
public static function htmlError(){
$run = new Run;
$run->pushHandler(new PrettyPageHandler);
$run->register();
}
}

49
cp/app/Lib/Mail.php Normal file
View file

@ -0,0 +1,49 @@
<?php namespace App\Lib;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
/**
* Mail
*
* @author Hezekiah O. <support@hezecom.com>
*/
class Mail
{
public static function send($subject, $body, $from=[], $to=[], $info=[])
{
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 0;
if(envi('MAIL_DRIVER')=='smtp') {
$mail->isSMTP();
$mail->Host = envi('MAIL_HOST');
$mail->SMTPAuth = true;
$mail->Username = envi('MAIL_USERNAME');
$mail->Password = envi('MAIL_PASSWORD');
$mail->SMTPSecure = envi('MAIL_ENCRYPTION');
$mail->Port = envi('MAIL_PORT');
}
elseif(envi('MAIL_DRIVER')=='sendmail') {
$mail->isSendmail();
}
else{
$mail->isMail();
}
$mail->setFrom($from['email'], $from['name']);
$mail->addAddress($to['email'], $to['name']);
//$mail->addAttachment('path/to/invoice1.pdf', 'invoice1.pdf');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
//echo 'Message has been sent';
return false;
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
}

68
cp/app/Lib/Redirect.php Normal file
View file

@ -0,0 +1,68 @@
<?php namespace App\Lib;
/**
* Redirect
*
* @author Hezekiah O. <support@hezecom.com>
*/
class Redirect
{
protected $name;
protected $status;
public function __construct($name=null,$status =301)
{
$this->name = $name;
$this->status = $status;
}
public function __destruct()
{
$this->redirect();
}
public function to($name,$status =301)
{
$this->name = $name;
$this->status = $status;
return $this;
}
public function route($name, $params1 =[], $params2=[],$status =301)
{
$this->name = route($name,$params1,$params2);
$this->status = $status;
return $this;
}
public function with($type, $message)
{
flash($type, $message);
return $this;
}
public function redirect()
{
if (getenv('SWOOLE_ENABLED')) {
// Running in Swoole
if (!$this->response->isSent()) {
$this->response = $this->response
->withHeader('Location', $this->name)
->withStatus($this->status);
} else {
$this->response->getBody()->write(
sprintf('<script>window.location.replace("%s");</script>', $this->name)
);
}
return $this->response;
} else {
// Running in nginx/caddy/etc
if (headers_sent() === false) {
header('Location: ' . $this->name, true, $this->status);
exit;
}
exit('window.location.replace("' . $this->name . '");');
}
}
}

37
cp/app/Lib/Validator.php Normal file
View file

@ -0,0 +1,37 @@
<?php
namespace App\Lib;
use Respect\Validation\Validator as Respect;
use Respect\Validation\Exceptions\NestedValidationException;
/**
* Validator
*
* @author Hezekiah O. <support@hezecom.com>
*/
class Validator
{
protected $errors;
public function validate($request, array $rules)
{
$data = $request->getParsedBody();
foreach ($rules as $field => $rule) {
$fieldName = str_replace('_',' ',$field);
try {
$rule->setName(ucfirst($fieldName))->assert($data[$field]);
} catch (NestedValidationException $e) {
$this->errors[$field] = $e->getMessages();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
public function failed()
{
return !empty($this->errors);
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
/**
* AuthMiddleware
*
* @author Hezekiah O. <support@hezecom.com>
*/
class AuthMiddleware extends Middleware
{
public function __invoke(Request $request, RequestHandler $handler)
{
if(! $this->container->get('auth')->isLogin()) {
return redirect()->route('login')->with('error', 'Access denied, you need to login.');
}
$response = $handler->handle($request);
return $response;
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
/**
* CsrfViewMiddleware
*
* @author Hezekiah O. <support@hezecom.com>
*/
class CsrfViewMiddleware extends Middleware
{
public function __invoke(Request $request, RequestHandler $handler)
{
$this->container->get('view')->getEnvironment()->addGlobal('csrf', [
'field' => '
<input type="hidden" name="'. $this->container->get('csrf')->getTokenNameKey() .'"
value="'. $this->container->get('csrf')->getTokenName() .'">
<input type="hidden" name="'. $this->container->get('csrf')->getTokenValueKey() .'"
value="'. $this->container->get('csrf')->getTokenValue() .'">
',
]);
$response = $handler->handle($request);
return $response;
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
/**
* GuestMiddleware
*
* @author Hezekiah O. <support@hezecom.com>
*/
class GuestMiddleware extends Middleware
{
public function __invoke(Request $request, RequestHandler $handler)
{
$response = $handler->handle($request);
if($this->container->get('auth')->isLogin()) {
return redirect()->route('home');
}
return $response;
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace App\Middleware;
use DI\Container;
/**
* Middleware
*
* @author Hezekiah O. <support@hezecom.com>
*/
class Middleware
{
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
/**
* OldInputMiddleware
*
* @author Hezekiah O. <support@hezecom.com>
*/
class OldInputMiddleware extends Middleware
{
public function __invoke(Request $request, RequestHandler $handler)
{
$this->container->get('view')->getEnvironment()->addGlobal('old', isset($_SESSION['old']) ? $_SESSION['old'] : '');
$_SESSION['old'] = $request->getParsedBody();
$response = $handler->handle($request);
return $response;
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
/**
* ValidationErrorsMiddleware
*
* @author Hezekiah O. <support@hezecom.com>
*/
class ValidationErrorsMiddleware extends Middleware
{
public function __invoke(Request $request, RequestHandler $handler)
{
$this->container->get('view')->getEnvironment()->addGlobal('errors', isset($_SESSION['errors']) ? $_SESSION['errors'] : '');
unset($_SESSION['errors']);
$response = $handler->handle($request);
return $response;
}
}

50
cp/app/Models/User.php Normal file
View file

@ -0,0 +1,50 @@
<?php
namespace App\Models;
use Pinga\Db\PdoDatabase;
class User
{
private $db;
public function __construct(PdoDatabase $db)
{
$this->db = $db;
}
public function getAllUsers()
{
return $this->db->select('SELECT * FROM users');
}
public function getUserById($id)
{
return $this->db->select('SELECT * FROM users WHERE id = ?', [$id])->fetch();
}
public function createUser($username, $email, $password)
{
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$this->db->insert('INSERT INTO users (username, email, password) VALUES (?, ?, ?)', [$username, $email, $hashedPassword]);
return $this->db->lastInsertId();
}
public function updateUser($id, $username, $email, $password)
{
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$this->db->update('UPDATE users SET username = ?, email = ?, password = ? WHERE id = ?', [$username, $email, $hashedPassword, $id]);
return true;
}
public function deleteUser($id)
{
$this->db->delete('DELETE FROM users WHERE id = ?', [$id]);
return true;
}
}