Showing posts with label Codeigniter Shield. Show all posts
Showing posts with label Codeigniter Shield. Show all posts

Sunday, July 12, 2026

Vue Codeigniter Integration

Let CodeIgniter serve the initial HTML page, and let Vue mount into a <div id="app"></div>. This gives you the benefits of CodeIgniter routing, sessions (Shield), CSRF, SEO-friendly pages, and future API/mobile support.

Recommended Project Structure

project-root/
├── app/
│   ├── Controllers/
│   │   └── Home.php
│   └── Views/
│       └── welcome_message.php
│
├── public/
│   ├── build/
│   │   ├── assets/
│   │   └── .vite/
│   ├── index.php
│   └── favicon.ico
│
├── frontend/
│   ├── src/
│   │   ├── main.js
│   │   ├── App.vue
│   │   └── router/
│   ├── index.html
│   └── vite.config.js

1. Build Vue

npm run build

This generates

public/build/
    assets/
        index-xxxxx.js
        index-xxxxx.css

2. Create the CodeIgniter View

app/Views/welcome_message.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <?= vite('frontend') ?>
</head>
<body>

<div id="app"></div>

</body>
</html>

3. Home Controller

<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    {
        return view('welcome_message');
    }
}

4. Routes

$routes->get('/', 'Home::index');

Now visiting

http://localhost/

loads the CI page.


5. Vue Entry

src/main.js

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

Vue will mount inside

<div id="app"></div>

6. During Development (Vite)

Instead of loading the built assets, load the Vite development server.

Create a helper:

<?php

function vite(string $entry = 'frontend')
{
    if (ENVIRONMENT === 'development')
    {
        return '
            <script type="module" src="http://localhost:5173/@vite/client"></script>
            <script type="module" src="http://localhost:5173/src/main.js"></script>
        ';
    }

    $manifest = json_decode(
        file_get_contents(FCPATH.'build/.vite/manifest.json'),
        true
    );

    $file = $manifest['src/main.js'];

    $html = '';

    if (isset($file['css'])) {
        foreach ($file['css'] as $css) {
            $html .= '<link rel="stylesheet" href="'.base_url('build/'.$css).'">';
        }
    }

    $html .= '<script type="module" src="'.base_url('build/'.$file['file']).'"></script>';

    return $html;
}

Then

<?= vite() ?>

works in both development and production.


7. Vue Router

Configure history mode.

import { createRouter, createWebHistory } from 'vue-router'

export default createRouter({
    history: createWebHistory(),
    routes: [
        // routes
    ]
})

Register it:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App)
    .use(router)
    .mount('#app')

8. Catch All Routes in CodeIgniter

If Vue Router handles navigation, make CodeIgniter always return the same view:

$routes->get('/', 'Home::index');

$routes->get('(:any)', 'Home::index');

or

$routes->add('(:any)', 'Home::index');

This allows routes like

/
/about
/products
/dashboard

to all load the Vue application.


9. CodeIgniter + Shield Authentication

Since CodeIgniter serves the page:

  • Shield sessions work normally.

  • CSRF protection remains available.

  • You can expose authenticated user data to Vue before it mounts if needed:

<script>
window.App = {
    user: <?= json_encode(auth()->user()) ?>
};
</script>

Then in Vue:

const user = window.App.user;

Architecture Recommendation

For CodeIgniter 4 + Vue + TailwindCSS + CodeIgniter Shield application (with future mobile API support), a clean architecture is:

Browser
   │
   ▼
CodeIgniter Route
   │
   ▼
Home Controller
   │
   ▼
welcome_message.php
   │
   ├── <div id="app"></div>
   ├── Inject authenticated user/session data
   └── Load Vite-built JS/CSS
            │
            ▼
         Vue App
            │
      Vue Router
            │
      Axios/Fetch API
            │
            ▼
CodeIgniter REST API
            │
      Shield Authentication
            │
        Database

This keeps CodeIgniter responsible for the initial request, authentication, and APIs, while Vue handles the entire client-side UI, which is scalable and aligns well with a future mobile application consuming the same REST APIs.

Wednesday, January 8, 2025

Codeigniter Shield Authorization

Codeigniter Shield Authorization

CodeIgniter Shield is the official authentication and authorization framework for CodeIgniter 4. It provides a flexible role-based access control (RBAC) system, allowing you to manage user permissions effectively.

Key Concepts:

Groups: Users can belong to multiple groups, which can represent traditional roles (e.g., admin, moderator) or be used to group users based on features or other criteria.

Permissions: Permissions define what actions a user is allowed to perform within your application. Permissions are typically associated with groups.

Users: Each user has a set of permissions based on the groups they belong to, and can also have permissions directly assigned to them.

Defining Groups:

Groups are defined in the Shield\Config\AuthGroups configuration file. Each group has a key, a title, and an optional description.

php
public array $groups = [
'superadmin' => [
'title' => 'Super Admin',
'description' => 'Optional description of the group.',
],
'editor' => [
'title' => 'Editor',
'description' => 'Can edit content.'
],
'user' => [
'title' => 'User',
'description' => 'Basic user access.'
]
];

Defining Permissions:

php
public array $permissions = [ 'superadmin.access' => 'Can access the sites admin area', 'superadmin.settings' => 'Can access the main site settings', 'editor.create' => 'Can view/edit site content', 'users.create' => 'Can create new non-admin users', 'users.edit' => 'Can edit existing non-admin users', 'users.delete' => 'Can delete existing non-admin users', ];

Checking Permissions:

You can check if a user has a specific permission using the can() method on the User entity. This method checks permissions within the groups the user belongs to, as well as any permissions directly assigned to the user.

php
if (! auth()->user()->can('users.create')) {
return redirect()->back()->with('error', 'You do not have permissions to access that page.');
}

Example:

Let's say you have a 'superadmin' group with the permission users.create. You can check if the current user has this permission like this:

php
if (auth()->user()->can('users.create')) {
// Allow user to create a new user
} else {
// Redirect or show an error message
}

Getting the Current User:

You can get the current user using the auth() helper function:

php
$user = auth()->user();

Adding Group To a User:

php
$user = auth()->user();
$user->addGroup('superadmin', 'editor');

Removing Group From a User:

php
$user = auth()->user(); $user->removeGroup('superadmin', 'editor');

Check if User Belongs to a Group:

php
$user = auth()->user(); if ($user->inGroup('superadmin')) { // do something }

In summary, CodeIgniter Shield's authorization system allows you to:

Define user groups with specific roles and permissions.

Assign users to one or more groups.

Check if a user has the necessary permissions to perform an action.

This provides a flexible and robust way to manage access control in your CodeIgniter application.

Advertisement

JBL Wave Buds 2 Ear Buds Wireless BluetoothV5.3, Active Noise Cancellation EarBuds,Multi Connect, App for Customized Extra Bass Eq, Relax Mode,Speed Charge, 40H Playback, Fast Pair, 4 Mics,IP54(Black)

Sony WF-C710N | Dual Noise Cancellation Wireless Bluetooth in Ear Earbuds | AI Call Quality | 40Hrs Battery W/O ANC | 30Hrs Battery with ANC - Blue

Monday, March 11, 2024

Codeigniter Shield - Install and Configure

Install Codeigniter Shield

Codeigniter Shield is the official authentication and authorization framework for codeigniter 4. It provides session authentication, in which the user ID and password is stored in the session for the subsequent requests to authenticate against. Basically, it has all the features that the modern website offers.

Sending email from website using Microsoft Office 365 OAuth2

Step 1: Register an Application in Microsoft Entra ID Sign in to the Microsoft Azure portal: Microsoft Azure Portal Navigate to: Microsoft E...