summaryrefslogtreecommitdiff
path: root/public/app/controllers/Auth.php
diff options
context:
space:
mode:
authorGeorge Halkiadakis <gchalkiadakis@sklavenitis.co.gr>2023-04-27 03:47:30 +0300
committerGeorge Halkiadakis <gchalkiadakis@sklavenitis.co.gr>2023-04-27 03:47:30 +0300
commit059e0d95d0c28bc5060e87e146eaf7411f51bf90 (patch)
tree7c21ac432f16dde2329a0d5954d70711eceb48e6 /public/app/controllers/Auth.php
parent26cd8ee99659ef1926c96a049c93645ffc9b169d (diff)
downloadgyraf1gov-059e0d95d0c28bc5060e87e146eaf7411f51bf90.tar.gz
gyraf1gov-059e0d95d0c28bc5060e87e146eaf7411f51bf90.tar.bz2
gyraf1gov-059e0d95d0c28bc5060e87e146eaf7411f51bf90.zip
skeleton commit; based on an anom project
Diffstat (limited to 'public/app/controllers/Auth.php')
-rw-r--r--public/app/controllers/Auth.php382
1 files changed, 382 insertions, 0 deletions
diff --git a/public/app/controllers/Auth.php b/public/app/controllers/Auth.php
new file mode 100644
index 0000000..4a6b9ed
--- /dev/null
+++ b/public/app/controllers/Auth.php
@@ -0,0 +1,382 @@
+<?php
+namespace app\controllers;
+
+use Registry;
+use Render;
+
+// user classes and models
+use app\extends\Classroom_user;
+use app\extends\Classroom_manager;
+use app\models\admin\User_model;
+
+use app\extends\Send_mail;
+use app\extends\Mail_jet;
+
+
+/** class Auth
+ *
+ * handles user's Authentication and Authorizarion
+ *
+ */
+class Auth {
+
+ /** login
+ *
+ * checks visitor's credentials;
+ * if valid, authenticates user
+ *
+ */
+ public static function login()
+ {
+ $req = Registry::get('REQUEST');
+
+ // get the record of the target user
+ $record = User_model::checkUser($req->POST['email']);
+
+ // if no user exists, return false
+ if ($record === false) return false;
+
+ // user is valid; check user password
+ // create a user object
+ $user = (new Classroom_user())
+ ->setID($record['id'])
+ ->setUserName($record['email'])
+ ->setName($record['first_name'] .' '. $record['last_name'])
+ ->setPassword($record['password'])
+ ->setEnabled($record['active']);
+
+ // let user manager to validate user credentials
+ $userManager = new Classroom_manager();
+
+ if ($userManager->isPasswordValid($user, $req->POST['password'])) {
+
+ // get user's security attributes
+ $attributes = User_Model::getUser($record['id']);
+ $roles = json_decode($attributes['Roles_json']);
+ $user
+ ->setRoles($roles)
+ ->setPrivileges(
+ array_merge(
+ json_decode($attributes['RootPrivileges_json']),
+ self::merge_lists_array(
+ json_decode($attributes['SubPrivileges_json'])
+ )
+ )
+ );
+
+ // regeneration session ID (prevent session fixation)
+ session_regenerate_id();
+ // set cookie for connected user
+ setcookie(
+ 'cluser',
+ 'connected;'. $user->getName(),
+ time()+60*60*8, // 8 hours
+ '/'
+ );
+
+ // check if admin (and redirect differently)
+ $is_admin = (!empty(array_intersect([1,2,3], $roles)));
+
+ // login OK, set Token in session
+ $userManager->createUserToken($user);
+ return [
+ 'success' => true,
+ 'goto' => $is_admin ? '/admin/lessons' : '/user/profile',
+ ];
+
+ } else {
+ return false;
+ }
+ }
+
+
+ /**
+ * merges an array of lists to one list
+ */
+ private static function merge_lists_array( $list )
+ {
+ $current = [];
+ foreach($list as $sublist) {
+ $current = array_merge($current, $sublist);
+ }
+ return $current;
+ }
+
+
+ /** activate
+ * resolves a call like: /account/activate?ticket=ca42d68cfba5fbbafeacc010b8e3a551
+ */
+ public static function activate()
+ {
+ $req = Registry::get('REQUEST');
+
+ // get the record of the target user
+ $check = User_model::activate($req->GET['ticket']);
+
+ if ($check == true) {
+ Render::view('/error/general', [
+ 'title' => ACCOUNT_ACTIVATED_TITLE,
+ 'message' => ACCOUNT_ACTIVATED_MESSAGE
+ ]);
+
+ } else {
+ Render::view('/error/general', [
+ 'title' => NOT_VALID_ACTIVATION_TITLE,
+ 'message' => NOT_VALID_ACTIVATION_MESSAGE
+ ]);
+ }
+
+ }
+
+ /** register
+ *
+ * Method for new user registration
+ *
+ */
+ public static function register()
+ {
+ $userManager = new Classroom_manager();
+ $req = Registry::get('REQUEST');
+
+ // create a salted password hash
+ $password = $userManager->cryptPassword($req->POST['password']);
+
+ // echo $password; print_r($req->POST); die(); // OK!
+
+ $user = (new Classroom_user())
+ ->setUserName($req->POST['email'])
+ ->setName($req->POST['name'] .' '. $req->POST['surname'])
+ ->setPassword($password)
+ ->setRoles([ READER ]) // Role: authorized reader
+ ->setPrivileges([]); // none privilege until acount confirmation
+
+ // create user record
+ $activation_code = User_model::registerUser($req->POST, $password);
+
+ // TODO:
+ // handle error on user registration
+ // ...
+ //
+ // if ($activatopn_code[] == -1) {
+ // return [
+ // 'success' => false,
+ // 'message' => REGISTRATION_USER_EXISTS
+ // ];
+ // }
+
+ $send_mail = Send_mail::send_activation_code([
+ 'email' => $req->POST['email'],
+ 'name' => $req->POST['name'] .' '. $req->POST['surname'],
+ 'code' => $activation_code['activation']
+ ]);
+
+ // Send replies
+ if ($send_mail) {
+ return [
+ 'success' => true,
+ 'message' => REGISTRATION_SUCCESS
+ ];
+
+ } else {
+ return [
+ 'success' => false,
+ 'message' => 'error on sending email'
+ ];
+ }
+
+ }
+
+ /** is_connected
+ * checks if the user is connected
+ *
+ * @return true|false
+ */
+ public static function is_connected()
+ {
+ $manager = new Classroom_manager();
+ if ($manager->hasUserToken()) {
+
+ // user is connected;
+ $token = $manager->getUserToken();
+ $user = $token->getUser();
+
+ return $user;
+
+ } else {
+ // user is not connected;
+ return false;
+ }
+ }
+
+
+ /** logout
+ *
+ * performs a secure logout;
+ * regenerates session; deletes cookies;
+ */
+ public static function logout()
+ {
+ $userManager = new Classroom_manager();
+ $userManager->logout();
+
+ // regeneration session ID (prevent session fixation)
+ session_regenerate_id();
+
+ // remove user-conected cookie
+ if (isset($_COOKIE['cluser'])) {
+ unset($_COOKIE['cluser']);
+ setcookie('cluser', '', -1, '/');
+ return true;
+
+ } else {
+ return false;
+ }
+ }
+
+
+
+ /** hasPermition( PERMIT )
+ *
+ * checks if the user owns the specified permition
+ * to access the source
+ *
+ */
+ public static function hasPermition($permit = [0])
+ {
+ if (in_array(0, $permit)) { // permision 0 means public
+ return true; // permision 0 is always granted
+ }
+
+ if ($user = self::is_connected() === false) { // if not connected
+ return false; // then no other permition is granted
+ }
+
+ if ($user instanceof UserInterface) {
+ return ( !empty( array_intersect($permit, $user->getPrivileges()) ) );
+ }
+ }
+
+
+ /** isAuthenticated()
+ *
+ * chechs if the user's roles and permitions
+ * satisfy the specified requirements
+ * to access the source
+ *
+ * @param $requirements (array of rules-array)
+ *
+ * example:
+ * [
+ * [
+ * role => [2, 3]
+ * permition => ['10', '12', '18']
+ * ],
+ * [
+ * role => [1 , 4]
+ * ],
+ * [
+ * permition => [ 3 ]
+ * ]
+ * ]
+ *
+ * defines (and parses to) a requirements rule of:
+ * [
+ * user should be creator or editor
+ * _AND_ have permition 10 or 12 or 18
+ * ]
+ * OR
+ * [
+ * user should be an administrator or developer
+ * ]
+ * OR
+ * [
+ * user should have permition #3
+ * ]
+ *
+ *
+ */
+ public static function isAuthorized($requirements)
+ {
+ $authorized = false;
+ foreach($requirements as $required) {
+
+ if (isset($required['role'])) { // if a role is required
+ if ( (self::isGranted($required['role'])) // authorize both role
+ && (self::hasPermition($required['permition'] ?? [ 0 ])) ) { // and permition
+ // $authorized = true;
+ return true;
+ }
+
+ } else { // else, if not is not required
+ if (self::hasPermition($required['permition'] ?? [ 0 ])) { // authorize permition
+ // $authorized = true;
+ return true;
+ }
+ }
+ }
+ return $authorized;
+ }
+
+
+ public static function forgot_pass()
+ {
+ }
+
+
+
+ public static function validate_otp()
+ {
+ }
+
+
+ /** allowRoles
+ *
+ * method filters access for certain roles
+ * if user is not grented acces, a forbiden message is sent and app ends._
+ * otherwise the method returns true (app will continue)
+ *
+ * @param $allowed (array) : array of allowed roles
+ * @return true or die();
+ */
+ public static function allowRoles($allowed)
+ {
+ $manager = new Classroom_manager();
+ if ($manager->isGranted($allowed)) { // if valid, return true (continue)
+ return true;
+
+ } else { // no user, no access; die._
+ Render::view('error/general', [
+ 'title' => 'Forbidden',
+ 'message' => 'Access is forbidden'
+ ]);
+ die();
+ return false; // this line will never run
+ }
+ }
+
+
+ /** hasValidRole
+ * like allowRoles() but dowes not stop execution
+ *
+ * @return true|false
+ */
+ public static function hasValidRole($allowed)
+ {
+ $manager = new Classroom_manager();
+ return ($manager->isGranted($allowed));
+ }
+
+
+ public static function in_admin_group()
+ {
+ $manager = new Classroom_manager();
+ return ($manager->isGranted([1, 2, 3]));
+ }
+
+
+
+}
+
+
+// NOTE:
+// check: https://netcorecloud.com/tutorials/send-an-email-via-gmail-smtp-server-using-php/ \ No newline at end of file