Laravel - Controlador de autenticación revisado -- php campo con authentication campo con laravel campo con controller camp codereview Relacionados El problema

Laravel - Revised Authentication Controller


4
vote

problema

Español

Estoy desarrollando una solicitud de capacitación de concientización sobre ingeniería social. Este es el foco de mi tesis para mi licenciatura. Esta será una solicitud de revisión de varias partes, sin embargo, si desea ver toda la aplicación, se puede encontrar en GitHub . Para esta solicitud, estoy buscando ver cómo mi AuthController revisado ( Solicitud inicial ) se establece arriba y lo efectivo que crees que podría ser. Abierto a cualquier y todas las sugerencias sobre cualquier faceta del código.

Una pregunta que todavía tengo, sin embargo, ¿hay algún beneficio para tener mi solicitud casi completamente estática?

Tenga en cuenta que esta aplicación está casi a probar, sin embargo, hay algunas piezas que podrían no ser pulidas.

authontroller

  <?php  namespace AppHttpControllers;  use AppLibrariesCryptor; use AppLibrariesErrorLogging; use AppLibrariesRandomObjectGeneration; use AppModelsSessions; use AppModelsTwo_Factor; use AppModelsUser; use AppModelsUser_Permissions; use IlluminateDatabaseQueryException; use IlluminateHttpRequest; use LeagueFlysystemException;  class AuthController extends Controller { /**  * create  * Create a new user instance after a valid registration.  *  * @param   Request         $request  * @return  User  */ public static function create(Request $request) {     try {         if($request->input('emailText') != $request->input('confirmEmailText')) {             return redirect()->route('register');         }          $email = $request->input('emailText');         $username = $request->input('usernameText');         $password = RandomObjectGeneration::random_str(intval(getenv('DEFAULT_LENGTH_PASSWORDS')),true);          $user = User::create([             'username' => $username,             'email' => $email,             'first_name' => $request->input('firstNameText'),             'last_name' => $request->input('lastNameText'),             'middle_initial' => $request->input('middleInitialText'),             'password' => password_hash($password,PASSWORD_DEFAULT),             'two_factor_enabled' => 0,         ]);          EmailController::sendNewAccountEmail($user,$password);         return redirect()->route('users');      } catch(QueryException $qe) {         if(strpos($qe->getMessage(),"1062 Duplicate entry 'admin'") !== false) {             return redirect()->route('register'); //return with username exists error         }         return redirect()->route('register'); //return with unknown error      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * authenticate  * Authenticates the user against the user's database object. Submits to 2FA if they have  * the option enabled, otherwise logs the user in.  *  * @param   Request         $request  * @return  IlluminateHttpRedirectResponse  */ public static function authenticate(Request $request) {     try {         $user = User::where('username',$request->input('usernameText'))->first();         $password = $request->input('passwordText');         if(empty($user) || !password_verify($password,$user->password)) {             return redirect()->route('login');         }          User::updateUser($user,$user->email,password_hash($password,PASSWORD_DEFAULT),$user->two_factor_enabled);          $session = Sessions::where('user_id',$user->id)->first();         if(!empty($session)) {             $session->delete();         }          $ip = $_SERVER['REMOTE_ADDR'];         $cryptor = new Cryptor();          if($user->two_factor_enabled === 1) {             $twoFactor = Two_Factor::where([                 'user_id' => $user->id, 'ip_address' => $ip             ])->first();             if(!empty($twoFactor)) {                 $twoFactor->delete();             }              $code = RandomObjectGeneration::random_str(6,false,'1234567890');             $twoFactor = Two_Factor::create([                 'user_id' => $user->id,                 'ip_address' => $_SERVER['REMOTE_ADDR'],                 'code' => password_hash($code,PASSWORD_DEFAULT)             ]);              EmailController::sendTwoFactorEmail($user,$code);              $newSession = Sessions::create([                 'user_id' => $user->id,                 'ip_address' => $ip,                 'two_factor_id' => $twoFactor->id,                 'authenticated' => 0             ]);              $encryptedSession = $cryptor->encrypt($newSession->id);             Session::put('sessionId',$encryptedSession);              return redirect()->route('2fa');         }          $newSession = Sessions::create([             'user_id' => $user->id,             'ip_address' => $ip,             'authenticated' => 1         ]);          $encryptedSession = $cryptor->encrypt($newSession->id);         Session::put('sessionId',$encryptedSession);          $intended = Session::pull('intended');         if($intended) {             return redirect()->to($intended);         }         return redirect()->route('authHome');      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * generateTwoFactorPage  * Route for generating the 2FA page.  *  * @return IlluminateHttpRedirectResponse | IlluminateViewView  */ public static function generateTwoFactorPage() {     try {         if(Session::has('sessionId')) {             $cryptor = new Cryptor();              $sessionId = $cryptor->decrypt(Session::get('sessionId'));             $session = Sessions::where('id',$sessionId)->first();              $sessionCheck = self::activeSessionCheck($session);             if(!is_null($sessionCheck)) {                 return $sessionCheck;             }              if(!is_null($session->two_factor_id)) {                 return view('auth.2fa');             }         }         return redirect()->route('login');      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * twoFactorVerify  * Validates the 2FA code to authenticate the user.  *  * @param   Request         $request  * @return  IlluminateHttpRedirectResponse  */ public static function twoFactorVerify(Request $request) {     try {         if(!Session::has('sessionId')) {             return redirect()->route('login');         }         $cryptor = new Cryptor();          $sessionId = $cryptor->decrypt(Session::get('sessionId'));         $session = Sessions::where('id',$sessionId)->first();          $sessionCheck = self::activeSessionCheck($session);         if(!is_null($sessionCheck)) {             return $sessionCheck;         }          $twoFactor = Two_Factor::where([             'user_id' => $session->user_id, 'ip_address' => $_SERVER['REMOTE_ADDR']         ])->first();          if(!password_verify($request->input('codeText'),$twoFactor->code)) {             return redirect()->route('2fa');         }          $session->update([             'two_factor_id' => null,             'authenticated' => 1         ]);          $twoFactor->delete();          $intended = Session::pull('intended');         if($intended) {             return redirect()->to($intended);         }         return redirect()->route('authHome');      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * resend2FA  * Generates and sends a new 2FA code.  *  * @return  IlluminateHttpRedirectResponse  */ public static function resend2FA() {     try {         if(!Session::has('sessionId')) {             return redirect()->route('login');         }         $cryptor = new Cryptor();          $sessionId = $cryptor->decrypt(Session::get('sessionId'));         $session = Sessions::where('id',$sessionId)->first();          $sessionCheck = self::activeSessionCheck($session);         if(!is_null($sessionCheck)) {             return $sessionCheck;         }          $user = User::where('id',$session->user_id)->first();         if(empty($user)) {             return self::logout();         }          $twoFactor = Two_Factor::where([             'user_id' => $session->user_id, 'ip_address' => $_SERVER['REMOTE_ADDR']         ])->first();         if(!empty($twoFactor)) {             $twoFactor->delete();         }          $code = RandomObjectGeneration::random_str(6, '1234567890');         Two_Factor::create([             'user_id' => $session->user_id,             'ip_address' => $_SERVER['REMOTE_ADDR'],             'code' => password_hash($code,PASSWORD_DEFAULT)         ]);          EmailController::sendTwoFactorEmail($user,$code);         return redirect()->route('2fa');      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * activeSessionCheck  * Helper function to check session objects.  *  * @param   Sessions    $session            The session to check.  * @return  IlluminateHttpRedirectResponse | null  */ private static function activeSessionCheck(Sessions $session) {     if($session->ip_address !== $_SERVER['REMOTE_ADDR']) {         $session->delete();         Session::forget('sessionId');         return redirect()->route('login');     }      if($session->authenticated === 1) {         return redirect()->route('authHome');     }     return null; }  /**  * check  * Validates if the user is authenticated on this IP Address.  *  * @return  bool  */ public static function check() {     if(!Session::has('sessionId')) {         return false;     }     $cryptor = new Cryptor();      $sessionId = $cryptor->decrypt(Session::get('sessionId'));     $session = Sessions::where('id', $sessionId)->first();      if($session->ip_address !== $_SERVER['REMOTE_ADDR']) {         $session->delete();         Session::forget('sessionId');         return false;     }     return true; }  /**  * adminCheck  * Validates if the user is an authenticated admin user.  *  * @return bool  */ public static function adminCheck() {     $check = self::check();     if(!$check) {         return $check;     }      $cryptor = new Cryptor();      $sessionId = $cryptor->decrypt(Session::get('sessionId'));     $session = Sessions::where('id', $sessionId)->first();      $user = User::where('id',$session->user_id)->first();     if(empty($user)) {         $session->delete();         Session::forget('sessionId');         return false;     }      if($user->user_type !== 1) {         return false;     }     return true; }  /**  * logout  * Removes session variables storing the authenticated account.  *  * @return  IlluminateHttpRedirectResponse  */ public static function logout() {     $cryptor = new Cryptor();      $sessionId = $cryptor->decrypt(Session::get('sessionId'));     Sessions::where('id', $sessionId)->first()->delete();     Session::forget('sessionId');      return redirect()->route('login'); }  /**  * generateLogin  * Generates the login page.  *  * @return IlluminateHttpRedirectResponse | IlluminateViewView  */ public static function generateLogin() {     if(self::check()) {         return redirect()->route('authHome');     }     return view('auth.login'); }  /**  * generateRegister  * Generates the register page if the user is an admin.  *  * @return IlluminateHttpRedirectResponse | IlluminateViewView  */ public static function generateRegister() {     if(self::adminCheck()) {         $permissions = User_Permissions::all();         $variables = array('permissions'=>$permissions);         return view('auth.register')->with($variables);     }     return abort('401'); }  /**  * authRequired  * Adds session variable for return redirect and then redirects to login page.  *  * @return  IlluminateHttpRedirectResponse  */ public static function authRequired() {     Session::put('intended',$_SERVER['REQUEST_URI']);     return redirect()->route('login'); } }   

Biblioteca de generación de objetos aleatorios

  <?php  namespace AppLibraries;  use DoctrineInstantiatorExceptionInvalidArgumentException;   class RandomObjectGeneration { const KEYSPACE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const PASSWORD_KEYSPACE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&';  /**  * random_str  * Generates a random string.  *  * @param   int                         $length         Length of string to be returned  * @param   bool                        $passwordFlag   Boolean flag identifying whether string will be a password  * @param   string                      $keyspace       Allowed characters to be used in string  * @throws  InvalidArgumentException  * @return  string  */ public static function random_str($length, $passwordFlag = false, $keyspace = RandomObjectGeneration::KEYSPACE) {     if($passwordFlag) {         $keyspace = RandomObjectGeneration::PASSWORD_KEYSPACE;     }     if(empty($length) || !is_int($length) || $length < 0) {         $message = 'Random String Generation: Length is Invalid. Length must be a positive integer. Value Provided: ' .             var_export($length);         throw new InvalidArgumentException($message);     }     if(empty($keyspace) || !is_string($keyspace)) {         $message = 'Random String Generation: Invalid Keyspace';         throw new InvalidArgumentException($message);     }     $str = '';     $max = mb_strlen($keyspace) - 1;     for ($i = 0; $i < $length; ++$i) {         $str .= $keyspace[random_int(0, $max)];     }     return $str; } }   

sessions Model

  <?php  namespace AppModels;  use IlluminateDatabaseEloquentModel;  class Sessions extends Model { protected $table = 'sessions';  protected $primaryKey = 'id';  protected $fillable = ['user_id',     'ip_address',     'two_factor_id',     'authenticated' ]; }   

ErrorLogging

  <?php  namespace AppLibraries;   use IlluminateSupportFacadesLog;  class ErrorLogging { public static function logError(Exception $e) {     $message = $e->getCode() . ': ' . $e->getMessage() . PHP_EOL;     $message .= $e->getTraceAsString() . PHP_EOL;     $message .= str_repeat('-',100) . PHP_EOL . PHP_EOL;     Log::error($message); } }   
Original en ingles

I'm developing a Social Engineering Awareness Training Application. This is the focus of my thesis for my undergraduate degree. This will be a multi-part review request, however, if you want to see the entire application, it can be found on GitHub. For this request, I'm looking to see how my revised AuthController (initial request) is set up and how effective you think it might be. I open to any and all suggestions about any facet of the code.

One question I still have, though, is there any benefit to having my application almost completely static?

Keep in mind that this application is nearly to testing, however, there are a few pieces that might not be polished.

AuthController

<?php  namespace App\Http\Controllers;  use App\Libraries\Cryptor; use App\Libraries\ErrorLogging; use App\Libraries\RandomObjectGeneration; use App\Models\Sessions; use App\Models\Two_Factor; use App\Models\User; use App\Models\User_Permissions; use Illuminate\Database\QueryException; use Illuminate\Http\Request; use League\Flysystem\Exception;  class AuthController extends Controller { /**  * create  * Create a new user instance after a valid registration.  *  * @param   Request         $request  * @return  User  */ public static function create(Request $request) {     try {         if($request->input('emailText') != $request->input('confirmEmailText')) {             return redirect()->route('register');         }          $email = $request->input('emailText');         $username = $request->input('usernameText');         $password = RandomObjectGeneration::random_str(intval(getenv('DEFAULT_LENGTH_PASSWORDS')),true);          $user = User::create([             'username' => $username,             'email' => $email,             'first_name' => $request->input('firstNameText'),             'last_name' => $request->input('lastNameText'),             'middle_initial' => $request->input('middleInitialText'),             'password' => password_hash($password,PASSWORD_DEFAULT),             'two_factor_enabled' => 0,         ]);          EmailController::sendNewAccountEmail($user,$password);         return redirect()->route('users');      } catch(QueryException $qe) {         if(strpos($qe->getMessage(),"1062 Duplicate entry 'admin'") !== false) {             return redirect()->route('register'); //return with username exists error         }         return redirect()->route('register'); //return with unknown error      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * authenticate  * Authenticates the user against the user's database object. Submits to 2FA if they have  * the option enabled, otherwise logs the user in.  *  * @param   Request         $request  * @return  \Illuminate\Http\RedirectResponse  */ public static function authenticate(Request $request) {     try {         $user = User::where('username',$request->input('usernameText'))->first();         $password = $request->input('passwordText');         if(empty($user) || !password_verify($password,$user->password)) {             return redirect()->route('login');         }          User::updateUser($user,$user->email,password_hash($password,PASSWORD_DEFAULT),$user->two_factor_enabled);          $session = Sessions::where('user_id',$user->id)->first();         if(!empty($session)) {             $session->delete();         }          $ip = $_SERVER['REMOTE_ADDR'];         $cryptor = new Cryptor();          if($user->two_factor_enabled === 1) {             $twoFactor = Two_Factor::where([                 'user_id' => $user->id, 'ip_address' => $ip             ])->first();             if(!empty($twoFactor)) {                 $twoFactor->delete();             }              $code = RandomObjectGeneration::random_str(6,false,'1234567890');             $twoFactor = Two_Factor::create([                 'user_id' => $user->id,                 'ip_address' => $_SERVER['REMOTE_ADDR'],                 'code' => password_hash($code,PASSWORD_DEFAULT)             ]);              EmailController::sendTwoFactorEmail($user,$code);              $newSession = Sessions::create([                 'user_id' => $user->id,                 'ip_address' => $ip,                 'two_factor_id' => $twoFactor->id,                 'authenticated' => 0             ]);              $encryptedSession = $cryptor->encrypt($newSession->id);             \Session::put('sessionId',$encryptedSession);              return redirect()->route('2fa');         }          $newSession = Sessions::create([             'user_id' => $user->id,             'ip_address' => $ip,             'authenticated' => 1         ]);          $encryptedSession = $cryptor->encrypt($newSession->id);         \Session::put('sessionId',$encryptedSession);          $intended = \Session::pull('intended');         if($intended) {             return redirect()->to($intended);         }         return redirect()->route('authHome');      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * generateTwoFactorPage  * Route for generating the 2FA page.  *  * @return \Illuminate\Http\RedirectResponse | \Illuminate\View\View  */ public static function generateTwoFactorPage() {     try {         if(\Session::has('sessionId')) {             $cryptor = new Cryptor();              $sessionId = $cryptor->decrypt(\Session::get('sessionId'));             $session = Sessions::where('id',$sessionId)->first();              $sessionCheck = self::activeSessionCheck($session);             if(!is_null($sessionCheck)) {                 return $sessionCheck;             }              if(!is_null($session->two_factor_id)) {                 return view('auth.2fa');             }         }         return redirect()->route('login');      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * twoFactorVerify  * Validates the 2FA code to authenticate the user.  *  * @param   Request         $request  * @return  \Illuminate\Http\RedirectResponse  */ public static function twoFactorVerify(Request $request) {     try {         if(!\Session::has('sessionId')) {             return redirect()->route('login');         }         $cryptor = new Cryptor();          $sessionId = $cryptor->decrypt(\Session::get('sessionId'));         $session = Sessions::where('id',$sessionId)->first();          $sessionCheck = self::activeSessionCheck($session);         if(!is_null($sessionCheck)) {             return $sessionCheck;         }          $twoFactor = Two_Factor::where([             'user_id' => $session->user_id, 'ip_address' => $_SERVER['REMOTE_ADDR']         ])->first();          if(!password_verify($request->input('codeText'),$twoFactor->code)) {             return redirect()->route('2fa');         }          $session->update([             'two_factor_id' => null,             'authenticated' => 1         ]);          $twoFactor->delete();          $intended = \Session::pull('intended');         if($intended) {             return redirect()->to($intended);         }         return redirect()->route('authHome');      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * resend2FA  * Generates and sends a new 2FA code.  *  * @return  \Illuminate\Http\RedirectResponse  */ public static function resend2FA() {     try {         if(!\Session::has('sessionId')) {             return redirect()->route('login');         }         $cryptor = new Cryptor();          $sessionId = $cryptor->decrypt(\Session::get('sessionId'));         $session = Sessions::where('id',$sessionId)->first();          $sessionCheck = self::activeSessionCheck($session);         if(!is_null($sessionCheck)) {             return $sessionCheck;         }          $user = User::where('id',$session->user_id)->first();         if(empty($user)) {             return self::logout();         }          $twoFactor = Two_Factor::where([             'user_id' => $session->user_id, 'ip_address' => $_SERVER['REMOTE_ADDR']         ])->first();         if(!empty($twoFactor)) {             $twoFactor->delete();         }          $code = RandomObjectGeneration::random_str(6, '1234567890');         Two_Factor::create([             'user_id' => $session->user_id,             'ip_address' => $_SERVER['REMOTE_ADDR'],             'code' => password_hash($code,PASSWORD_DEFAULT)         ]);          EmailController::sendTwoFactorEmail($user,$code);         return redirect()->route('2fa');      } catch(Exception $e) {         ErrorLogging::logError($e);         return abort('500');     } }  /**  * activeSessionCheck  * Helper function to check session objects.  *  * @param   Sessions    $session            The session to check.  * @return  \Illuminate\Http\RedirectResponse | null  */ private static function activeSessionCheck(Sessions $session) {     if($session->ip_address !== $_SERVER['REMOTE_ADDR']) {         $session->delete();         \Session::forget('sessionId');         return redirect()->route('login');     }      if($session->authenticated === 1) {         return redirect()->route('authHome');     }     return null; }  /**  * check  * Validates if the user is authenticated on this IP Address.  *  * @return  bool  */ public static function check() {     if(!\Session::has('sessionId')) {         return false;     }     $cryptor = new Cryptor();      $sessionId = $cryptor->decrypt(\Session::get('sessionId'));     $session = Sessions::where('id', $sessionId)->first();      if($session->ip_address !== $_SERVER['REMOTE_ADDR']) {         $session->delete();         \Session::forget('sessionId');         return false;     }     return true; }  /**  * adminCheck  * Validates if the user is an authenticated admin user.  *  * @return bool  */ public static function adminCheck() {     $check = self::check();     if(!$check) {         return $check;     }      $cryptor = new Cryptor();      $sessionId = $cryptor->decrypt(\Session::get('sessionId'));     $session = Sessions::where('id', $sessionId)->first();      $user = User::where('id',$session->user_id)->first();     if(empty($user)) {         $session->delete();         \Session::forget('sessionId');         return false;     }      if($user->user_type !== 1) {         return false;     }     return true; }  /**  * logout  * Removes session variables storing the authenticated account.  *  * @return  \Illuminate\Http\RedirectResponse  */ public static function logout() {     $cryptor = new Cryptor();      $sessionId = $cryptor->decrypt(\Session::get('sessionId'));     Sessions::where('id', $sessionId)->first()->delete();     \Session::forget('sessionId');      return redirect()->route('login'); }  /**  * generateLogin  * Generates the login page.  *  * @return \Illuminate\Http\RedirectResponse | \Illuminate\View\View  */ public static function generateLogin() {     if(self::check()) {         return redirect()->route('authHome');     }     return view('auth.login'); }  /**  * generateRegister  * Generates the register page if the user is an admin.  *  * @return \Illuminate\Http\RedirectResponse | \Illuminate\View\View  */ public static function generateRegister() {     if(self::adminCheck()) {         $permissions = User_Permissions::all();         $variables = array('permissions'=>$permissions);         return view('auth.register')->with($variables);     }     return abort('401'); }  /**  * authRequired  * Adds session variable for return redirect and then redirects to login page.  *  * @return  \Illuminate\Http\RedirectResponse  */ public static function authRequired() {     \Session::put('intended',$_SERVER['REQUEST_URI']);     return redirect()->route('login'); } } 

Random Object Generation Library

<?php  namespace App\Libraries;  use Doctrine\Instantiator\Exception\InvalidArgumentException;   class RandomObjectGeneration { const KEYSPACE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const PASSWORD_KEYSPACE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&';  /**  * random_str  * Generates a random string.  *  * @param   int                         $length         Length of string to be returned  * @param   bool                        $passwordFlag   Boolean flag identifying whether string will be a password  * @param   string                      $keyspace       Allowed characters to be used in string  * @throws  InvalidArgumentException  * @return  string  */ public static function random_str($length, $passwordFlag = false, $keyspace = RandomObjectGeneration::KEYSPACE) {     if($passwordFlag) {         $keyspace = RandomObjectGeneration::PASSWORD_KEYSPACE;     }     if(empty($length) || !is_int($length) || $length < 0) {         $message = 'Random String Generation: Length is Invalid. Length must be a positive integer. Value Provided: ' .             var_export($length);         throw new InvalidArgumentException($message);     }     if(empty($keyspace) || !is_string($keyspace)) {         $message = 'Random String Generation: Invalid Keyspace';         throw new InvalidArgumentException($message);     }     $str = '';     $max = mb_strlen($keyspace) - 1;     for ($i = 0; $i < $length; ++$i) {         $str .= $keyspace[random_int(0, $max)];     }     return $str; } } 

Sessions Model

<?php  namespace App\Models;  use Illuminate\Database\Eloquent\Model;  class Sessions extends Model { protected $table = 'sessions';  protected $primaryKey = 'id';  protected $fillable = ['user_id',     'ip_address',     'two_factor_id',     'authenticated' ]; } 

ErrorLogging

<?php  namespace App\Libraries;   use Illuminate\Support\Facades\Log;  class ErrorLogging { public static function logError(\Exception $e) {     $message = $e->getCode() . ': ' . $e->getMessage() . PHP_EOL;     $message .= $e->getTraceAsString() . PHP_EOL;     $message .= str_repeat('-',100) . PHP_EOL . PHP_EOL;     Log::error($message); } } 
           
       
       

Lista de respuestas

1
 
vote
vote
La mejor respuesta
 

Descargo de responsabilidad:

Recomiendo encarecidamente usar las funcionalidades construidas en Laraver para esto, pero como se "aconseje en contra" usarlo y esto es un trabajo universitario, a continuación es mi revisión:

Vamos a empezar con AuthController .


create1 MÉTODO:

este código:

  if($request->input('emailText') != $request->input('confirmEmailText')) {     return redirect()->route('register'); }   

Sugeriría primero asegurarse de que email no está vacío y es un correo electrónico válido.

En su lugar, crearía un 9988776655544334 .

  <?php  namespace AppHttpRequests;  use IlluminateFoundationHttpFormRequest;  class CreateUserRequest extends FormRequest {     public function authorize()     {         return true; // Change this as per your needs     }      public function rules()     {         return [             'emailText' => 'required|email',             'confirmEmailText' => 'same:emailText',             'usernameText' => 'required',             //...         ];     } }   

Luego, puede especificarlo como un tipo de su parámetro "9988776655544336 como este:

  public static function create(CreateUserRequest $request) {   

Además, asegúrese de revisar el reglas de validación actualmente disponibles y cómo crear el tuyo.

Por ejemplo, estas líneas:

  if(strpos($qe->getMessage(),"1062 Duplicate entry 'admin'") !== false) {             return redirect()->route('register'); //return with username exists error         }   

se puede evitar con la siguiente regla: 'email' => 'unique:users,username'

Entonces, ¿cómo se evalúan las reglas de validación? Todo lo que necesitas hacer es Escriba la solicitud de su método de controlador. La forma entrante La solicitud se valida antes de llamar al método del controlador, que significa No necesita desordenar su controlador con ninguna lógica de validación.

entonces, esta línea:

  create0  

Le sugiero usar eventos y observadores elocuentes . Si leerá los documentos, estoy seguro de que entenderá cómo usarlos.


create1 MÉTODO:

Como dije antes, la validación debe estar en un 99887766555443312 .

Luego, en lugar de create3 y create4

Sugeriría usar solo create5 y create6 . Se ve mucho más limpio.


Actualizará esta respuesta con la revisión de otros métodos de este controlador en breve.


general:

Conversiones de nombres: Use sustantivos singulares para nombres de clase.

Entonces, en lugar de create7 , yo usaría create8 o mejor 99887776655443319 . En lugar de if($request->input('emailText') != $request->input('confirmEmailText')) { return redirect()->route('register'); } 0 , yo usaría if($request->input('emailText') != $request->input('confirmEmailText')) { return redirect()->route('register'); } 1 o mejor if($request->input('emailText') != $request->input('confirmEmailText')) { return redirect()->route('register'); } 2 . Lo mismo ocurre con if($request->input('emailText') != $request->input('confirmEmailText')) { return redirect()->route('register'); } 3 : if($request->input('emailText') != $request->input('confirmEmailText')) { return redirect()->route('register'); } 4 es mejor. Buena respuesta sobre esto aquí .

También he notado que todos sus métodos son if($request->input('emailText') != $request->input('confirmEmailText')) { return redirect()->route('register'); } 5 , sin embargo, no estoy seguro de entender por qué.

 

Disclaimer:

I strongly recommend to use Laravel built in functionalities for this, but since it's "advised against" using it and this is a university work, below is my review:

Let's start with AuthController.


create method:

This code:

if($request->input('emailText') != $request->input('confirmEmailText')) {     return redirect()->route('register'); } 

I would suggest first making sure that email value is not empty and that is a valid e-mail.

Instead, I would create a custom FormRequest.

<?php  namespace App\Http\Requests;  use Illuminate\Foundation\Http\FormRequest;  class CreateUserRequest extends FormRequest {     public function authorize()     {         return true; // Change this as per your needs     }      public function rules()     {         return [             'emailText' => 'required|email',             'confirmEmailText' => 'same:emailText',             'usernameText' => 'required',             //...         ];     } } 

Then, you can just specify it as a type of your $request parameter like this:

public static function create(CreateUserRequest $request) { 

Also, make sure you check the currently available validation rules and how to create your own.

For example, this lines:

if(strpos($qe->getMessage(),"1062 Duplicate entry 'admin'") !== false) {             return redirect()->route('register'); //return with username exists error         } 

can be avoided with the following rule: 'email' => 'unique:users,username'

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic.

Then, this line:

EmailController::sendNewAccountEmail($user,$password); 

I suggesting using Eloquent Events and Observers. If you will read the docs, I am sure you will understand how to use them.


authenticate method:

As i said before, validation should be in a separate FormRequest.

Then, instead of \Session::put('sessionId',$encryptedSession); and \Session::pull('intended')

I would suggest using just session(['sessionId' => '$encryptedSession']) and session('intended'). It looks much more clean.


Will update this answer with the review of other methods from this controller shortly.


General:

Naming conversions: Use singular nouns for class names.

So, instead of SessionsModel, I would use SessionModel or better Session. Instead of ErrorLogging, I would use ErrorLogger or better Logger. The same goes for RandomObjectGeneration: RandomObjectGenerator is better. Nice answer about this here.

I have also noticed all your methods are static, however I am not sure I understand why.

 
 
 
 

Relacionados problema

2  Lógica de negocios en controlador  ( Business logic in controller ) 
LED por la premisa recientemente leída "Controladores magros y modelos de grasa" He llegado a la conclusión de que mi controlador podría ser demasiado gordo ...

14  Lista de AngularJS TODO - ¿demasiada lógica del controlador?  ( Angularjs todo list too much controller logic ) 
Estoy empezando una aplicación angular y me preguntaba si estoy en el camino correcto con esto. Trabajé en mi última aplicación angular cuando era solo un jov...

-1  Practicando los servlets de Java, MySQL y JSON - Seguimiento  ( Practicing java servlets mysql and json follow up ) 
(consulte la iteración anterior .) Qué es nuevo He incorporado todos los puntos de la respuesta de Dmytro Maslenko . Mi código parece un poco más ordena...

4  Búsqueda y filtro en MVC3 Razor usando LINQ  ( Search and filter in mvc3 razor using linq ) 
Este código funciona bien, pero no me gusta todo el if else . Si sigo agregando campo para filtrar, se va a ensuciar. No estoy usando EF y no puedo en esto...

-2  Configuración de la barra de pestañas, la navegación y las vistas de los controladores en iOS  ( Setting up tab bar navigation and view controllers in ios ) 
Soy nuevo en el desarrollo de iOS. Escribí este código, pero la compañía dijo que esta es mala arquitectura y no es aceptable. Quiero mejorar este código. ...

3  Sistema de votación de Laravel  ( Laravel voting system ) 
He escrito una clase de votación en Laravel. Utiliza los sitios de votación API para verificar si el usuario ha votado hoy. Solo se permite que un usuario vot...

1  Haciendo $ _post de la manera correcta  ( Doing post the right way ) 
No estoy seguro de si estoy manejando correctamente $_POST Datos en MVC PATTEL: dummy $_POST Datos $_POST = array( "menu" => array( "ke...

28  Prueba de unidad un controlador en rubí en los rieles  ( Unit testing a controller in ruby on rails ) 
Tengo la intención de que esto sea una pregunta general sobre cómo escribir un conjunto efectivo de casos de prueba para una acción de controlador. Incluyo ...

5  Juego de Trivia de AngularJS - Controlador de separación de la Directiva  ( Angularjs trivia game separating controller from directive ) 
Estoy creando un juego de trivia (propósitos puramente para aprender) usando angularjs , nodejs y mongodb. Mi preocupación está relacionada con la forma en ...

1  Reemplazo de una clase de servicio de aplicación con múltiples manipuladores de comando  ( Replacing an application service class with multiple command handlers ) 
Tengo un controlador que utiliza un servicio de aplicación para lograr sus tareas. La clase de servicio está comenzando a cultivar grandes y desarrollando múl...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos