Credentials Authentication

Credentials authentication allows users to sign in to applications using their email address and password. This approach requires users to create and remember new credentials for each application they use. It also provides developers with a secure and reliable way to authenticate users without having to rely on third-party services for authentication.

Prisma PHP supports credentials authentication through the use of email and password fields in your application's user database. By integrating credentials authentication into your application, you can allow users to sign in using their email address and password, making it easier for users to access your application and for developers to implement user authentication and authorization features.

Setting Up Credentials Authentication

Setting up credentials authentication in Prisma PHP involves creating a user database with email and password fields to store user credentials securely. To get started, you'll need to define a user model with email and password fields in your Prisma schema and generate the necessary database migrations to create the user table in your database. Once you have the user database set up, you can implement credentials authentication in your Prisma PHP application to enable users to sign in using their email address and password.

Creating a User Model

To create a user model with email and password fields in your Prisma schema, you can define a new model in your schema.prisma file with the following fields:

model User {
    id            String    @id @default(cuid())
    name          String?
    email         String?   @unique
    password      String?
    emailVerified DateTime?
    image         String?
  
    roleId   Int?
    userRole UserRole? @relation(fields: [roleId], references: [id])
  
    @@map("Users")
  }
  
  model UserRole {
    id   Int    @id @default(autoincrement())
    name String @unique
  
    user User[]
  }

Remember to generate your PHP classes for this to work by running the following command in your terminal:

npx php generate class

For more info go to Prisma PHP Command.

In this example, we're defining a user model with an id field that auto-increments for each new user, an email field that is unique for each user, and a password field that stores the user's password securely. The email field is marked as unique to ensure that each user has a unique email address, and the password field is used to store the user's password securely in the database, always hashed and salted.

Generating Database Migrations

After defining the user model in your Prisma schema, you'll need to generate database migrations to create the user table in your database. To generate a new migration, or update the existing migration, go to Prisma Commands

Implementing Credentials Authentication

Once you've created the user database with email and password fields, you can implement credentials authentication in your Prisma PHP application by verifying user credentials during the sign-in process. To authenticate users, you'll need to compare the email and password provided by the user with the email and password stored in the user database. If the credentials match, you can grant the user access to the application; otherwise, you can display an error message indicating that the credentials are invalid.

register a user, you need to create a register route form to allow users to create an account and store their credentials in the database.

Here's an example of how you can implement a register form in Prisma PHP:

first create your register route in your app directory src/app/auth/register/index.php this is just a example route and add the following code:

<?php

  use Lib\Auth\Auth;
  use Lib\Prisma\Classes\Prisma;
  use Lib\Validator;
  use Lib\StateManager;
  use Lib\Request;
  
  $auth = Auth::getInstance();
  
  if ($auth->isAuthenticated()) {
      Request::redirect('/dashboard');
  }
    
  $message = StateManager::getState('message');
  $name = StateManager::getState('name');
  $email = StateManager::getState('email');
  $password = StateManager::getState('password');
  $confirmPassword = StateManager::getState('password');
  
  function register($data)
  {
      global $name, $email, $password, $confirmPassword;
  
      StateManager::setState('name', $data->name);
      StateManager::setState('email', $data->email);
      StateManager::setState('password', $data->password);
      StateManager::setState('confirmPassword', $data->confirmPassword);
  
    if (!Validator::string($name) || !Validator::email($email) || !Validator::string($password) || !Validator::string  ($confirmPassword)) {
          StateManager::setState('message', 'All fields are required');
      } elseif ($password !== $confirmPassword) {
          StateManager::setState('message', 'Passwords do not match');
      } else {
          $prisma = Prisma::getInstance();
          $userExist = $prisma->user->findUnique([
              'where' => [
                  'email' => $email
              ]
          ]);
  
          if ($userExist) {
              StateManager::setState('message', 'User already exist');
          } else {
              $prisma->user->create([
                  'data' => [
                      'name' => $name,
                      'email' => $email,
                      'password' => password_hash($password, PASSWORD_DEFAULT),
                      'userRole' => [
                          'connectOrCreate' => [
                              'where' => [
                                  'name' => 'User'
                              ],
                              'create' => [
                                  'name' => 'User'
                              ]
                          ]
                      ]
                  ]
              ]);
  
              Request::redirect('/auth/login');
          }
      }
  }
  
  ?>

  <!-- Your register form here -->

After creating the register form, you can create a login form to allow users to sign in to the application using their email address and password. Here's an example of how you can implement a login form in Prisma PHP:

first create your login route in your app directory src/app/auth/login/index.php this is just a example route and add the following code:

<?php

  use Lib\StateManager;
  use Lib\Validator;
  use Lib\Prisma\Classes\Prisma;
  use Lib\Auth\Auth;
  
  $auth = Auth::getInstance();
  
  if ($auth->isAuthenticated()) {
      Request::redirect('/dashboard');
  }

  $email = StateManager::getState('email');
  $password = StateManager::getState('password');
  $errorMessages = StateManager::getState('errorMessages');
  
  function login($data)
  {
      global $email, $password, $auth;
  
      StateManager::setState('email', $data->email);
      StateManager::setState('password', $data->password);
  
      if (!Validator::email($email)) {
          StateManager::setState('errorMessages', 'Invalid email address');
          return;
      }
  
      if (!Validator::string($password)) {
          StateManager::setState('errorMessages', 'Password is required');
          return;
      }
  
      $prisma = Prisma::getInstance();
      $user = $prisma->user->findUnique([
          'where' => [
              'email' => $email
          ]
      ], true);
  
      if (!$user) {
          StateManager::setState('errorMessages', 'User not found');
          return;
      }
  
      if (!password_verify($password, $user->password)) {
          StateManager::setState('errorMessages', 'Invalid password');
          return;
      }
  
      $auth->sigIn($user);
  
      if ($auth->isAuthenticated()) {
          Request::redirect('/dashboard');
      }
  }
  
  ?>
  
  <!-- Your register form here -->

After creating the login form, you can implement credentials authentication in your Prisma PHP application by verifying user credentials during the sign-in process. To authenticate users, you'll need to compare the email and password provided by the user with the email and password stored in the user database. If the credentials match, you can grant the user access to the application; otherwise, you can display an error message indicating that the credentials are invalid.

Conclusion

By setting up credentials authentication in Prisma PHP, you can enable users to sign in to your application using their email address and password. This approach provides a secure and reliable way to authenticate users without having to rely on third-party services for authentication. With credentials authentication, you can create a user database with email and password fields to store user credentials securely and implement user authentication and authorization features in your Prisma PHP application.