Advertisement
AnshorFalahi

class AuthController

Nov 3rd, 2024
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 13.86 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Myth\Auth\Controllers;
  4.  
  5. use CodeIgniter\Controller;
  6. use CodeIgniter\Session\Session;
  7. use Myth\Auth\Config\Auth as AuthConfig;
  8. use Myth\Auth\Entities\User;
  9. use Myth\Auth\Models\UserModel;
  10.  
  11. class AuthController extends Controller
  12. {
  13.     protected $auth;
  14.  
  15.     /**
  16.      * @var AuthConfig
  17.      */
  18.     protected $config;
  19.  
  20.     /**
  21.      * @var Session
  22.      */
  23.     protected $session;
  24.  
  25.     public function __construct()
  26.     {
  27.         // Most services in this controller require
  28.         // the session to be started - so fire it up!
  29.         $this->session = service('session');
  30.  
  31.         $this->config = config('Auth');
  32.         $this->auth   = service('authentication');
  33.     }
  34.  
  35.     //--------------------------------------------------------------------
  36.     // Login/out
  37.     //--------------------------------------------------------------------
  38.  
  39.     /**
  40.      * Displays the login form, or redirects
  41.      * the user to their destination/home if
  42.      * they are already logged in.
  43.      */
  44.     public function login()
  45.     {
  46.         // No need to show a login form if the user
  47.         // is already logged in.
  48.         if ($this->auth->check()) {
  49.             $redirectURL = session('redirect_url') ?? site_url('/');
  50.             unset($_SESSION['redirect_url']);
  51.  
  52.             return redirect()->to($redirectURL);
  53.         }
  54.  
  55.         // Set a return URL if none is specified
  56.         $_SESSION['redirect_url'] = session('redirect_url') ?? previous_url() ?? site_url('/');
  57.  
  58.         return $this->_render($this->config->views['login'], ['config' => $this->config]);
  59.     }
  60.  
  61.     /**
  62.      * Attempts to verify the user's credentials
  63.      * through a POST request.
  64.      */
  65.     public function attemptLogin()
  66.     {
  67.         $rules = [
  68.             'login'    => 'required',
  69.             'password' => 'required',
  70.         ];
  71.         if ($this->config->validFields === ['email']) {
  72.             $rules['login'] .= '|valid_email';
  73.         }
  74.  
  75.         if (! $this->validate($rules)) {
  76.             return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
  77.         }
  78.  
  79.         $login    = $this->request->getPost('login');
  80.         $password = $this->request->getPost('password');
  81.         $remember = (bool) $this->request->getPost('remember');
  82.  
  83.         // Determine credential type
  84.         $type = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
  85.  
  86.         // Try to log them in...
  87.         if (! $this->auth->attempt([$type => $login, 'password' => $password], $remember)) {
  88.             return redirect()->back()->withInput()->with('error', $this->auth->error() ?? lang('Auth.badAttempt'));
  89.         }
  90.  
  91.         // Is the user being forced to reset their password?
  92.         if ($this->auth->user()->force_pass_reset === true) {
  93.             return redirect()->to(route_to('reset-password') . '?token=' . $this->auth->user()->reset_hash)->withCookies();
  94.         }
  95.  
  96.         $redirectURL = session('redirect_url') ?? site_url('/');
  97.         unset($_SESSION['redirect_url']);
  98.  
  99.         return redirect()->to($redirectURL)->withCookies()->with('message', lang('Auth.loginSuccess'));
  100.     }
  101.  
  102.     /**
  103.      * Log the user out.
  104.      */
  105.     public function logout()
  106.     {
  107.         if ($this->auth->check()) {
  108.             $this->auth->logout();
  109.         }
  110.  
  111.         return redirect()->to(site_url('/'));
  112.     }
  113.  
  114.     //--------------------------------------------------------------------
  115.     // Register
  116.     //--------------------------------------------------------------------
  117.  
  118.     /**
  119.      * Displays the user registration page.
  120.      */
  121.     public function register()
  122.     {
  123.         // check if already logged in.
  124.         if ($this->auth->check()) {
  125.             return redirect()->back();
  126.         }
  127.  
  128.         // Check if registration is allowed
  129.         if (! $this->config->allowRegistration) {
  130.             return redirect()->back()->withInput()->with('error', lang('Auth.registerDisabled'));
  131.         }
  132.  
  133.         return $this->_render($this->config->views['register'], ['config' => $this->config]);
  134.     }
  135.  
  136.     /**
  137.      * Attempt to register a new user.
  138.      */
  139.     public function attemptRegister()
  140.     {
  141.         // Check if registration is allowed
  142.         if (! $this->config->allowRegistration) {
  143.             return redirect()->back()->withInput()->with('error', lang('Auth.registerDisabled'));
  144.         }
  145.  
  146.         $users = model(UserModel::class);
  147.  
  148.         // Validate basics first since some password rules rely on these fields
  149.         $rules = config('Validation')->registrationRules ?? [
  150.             'username' => 'required|alpha_numeric_space|min_length[3]|max_length[30]|is_unique[users.username]',
  151.             'email'    => 'required|valid_email|is_unique[users.email]',
  152.         ];
  153.  
  154.         if (! $this->validate($rules)) {
  155.             return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
  156.         }
  157.  
  158.         // Validate passwords since they can only be validated properly here
  159.         $rules = [
  160.             'password'     => 'required|strong_password',
  161.             'pass_confirm' => 'required|matches[password]',
  162.         ];
  163.  
  164.         if (! $this->validate($rules)) {
  165.             return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
  166.         }
  167.  
  168.         // Save the user
  169.         $allowedPostFields = array_merge(['password'], $this->config->validFields, $this->config->personalFields);
  170.         $user              = new User($this->request->getPost($allowedPostFields));
  171.  
  172.         $this->config->requireActivation === null ? $user->activate() : $user->generateActivateHash();
  173.  
  174.         // Ensure default group gets assigned if set
  175.         if (! empty($this->config->defaultUserGroup)) {
  176.             $users = $users->withGroup($this->config->defaultUserGroup);
  177.         }
  178.  
  179.         if (! $users->save($user)) {
  180.             return redirect()->back()->withInput()->with('errors', $users->errors());
  181.         }
  182.  
  183.         if ($this->config->requireActivation !== null) {
  184.             $activator = service('activator');
  185.             $sent      = $activator->send($user);
  186.  
  187.             if (! $sent) {
  188.                 return redirect()->back()->withInput()->with('error', $activator->error() ?? lang('Auth.unknownError'));
  189.             }
  190.  
  191.             // Success!
  192.             return redirect()->route('login')->with('message', lang('Auth.activationSuccess'));
  193.         }
  194.  
  195.         // Success!
  196.         return redirect()->route('login')->with('message', lang('Auth.registerSuccess'));
  197.     }
  198.  
  199.     //--------------------------------------------------------------------
  200.     // Forgot Password
  201.     //--------------------------------------------------------------------
  202.  
  203.     /**
  204.      * Displays the forgot password form.
  205.      */
  206.     public function forgotPassword()
  207.     {
  208.         if ($this->config->activeResetter === null) {
  209.             return redirect()->route('login')->with('error', lang('Auth.forgotDisabled'));
  210.         }
  211.  
  212.         return $this->_render($this->config->views['forgot'], ['config' => $this->config]);
  213.     }
  214.  
  215.     /**
  216.      * Attempts to find a user account with that password
  217.      * and send password reset instructions to them.
  218.      */
  219.     public function attemptForgot($email = false)
  220.     {
  221.         if ($this->config->activeResetter === null) {
  222.             return redirect()->route('login')->with('error', lang('Auth.forgotDisabled'));
  223.         }
  224.  
  225.         if (!$email) {
  226.             $rules = [
  227.                 'email' => [
  228.                     'label' => lang('Auth.emailAddress'),
  229.                     'rules' => 'required|valid_email',
  230.                 ],
  231.             ];
  232.  
  233.             if (!$this->validate($rules)) {
  234.                 return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
  235.             }
  236.         }
  237.  
  238.         $users = model(UserModel::class);
  239.  
  240.         if ($email) {
  241.             $user = $users->where('email', $email)->first();
  242.         } else {
  243.             $user = $users->where('email', $this->request->getPost('email'))->first();
  244.         }
  245.  
  246.         if (null === $user) {
  247.             return redirect()->back()->with('error', lang('Auth.forgotNoUser'));
  248.         }
  249.  
  250.         // Save the reset hash /
  251.         $user->generateResetHash();
  252.         $users->save($user);
  253.  
  254.         $resetter = service('resetter');
  255.         $sent     = $resetter->send($user);
  256.  
  257.         if (!$sent) {
  258.             return redirect()->back()->withInput()->with('error', $resetter->error() ?? lang('Auth.unknownError'));
  259.         }
  260.  
  261.         return redirect()->route('reset-password')->with('message', lang('Auth.forgotEmailSent'));
  262.     }
  263.  
  264.     /**
  265.      * Displays the Reset Password form.
  266.      */
  267.     public function resetPassword()
  268.     {
  269.         if ($this->config->activeResetter === null) {
  270.             return redirect()->route('login')->with('error', lang('Auth.forgotDisabled'));
  271.         }
  272.  
  273.         $token = $this->request->getGet('token');
  274.  
  275.         return $this->_render($this->config->views['reset'], [
  276.             'config' => $this->config,
  277.             'token'  => $token,
  278.         ]);
  279.     }
  280.  
  281.     /**
  282.      * Verifies the code with the email and saves the new password,
  283.      * if they all pass validation.
  284.      *
  285.      * @return mixed
  286.      */
  287.     public function attemptReset()
  288.     {
  289.         if ($this->config->activeResetter === null) {
  290.             return redirect()->route('login')->with('error', lang('Auth.forgotDisabled'));
  291.         }
  292.  
  293.         $users = model(UserModel::class);
  294.  
  295.         // First things first - log the reset attempt.
  296.         $users->logResetAttempt(
  297.             $this->request->getPost('email'),
  298.             $this->request->getPost('token'),
  299.             $this->request->getIPAddress(),
  300.             (string) $this->request->getUserAgent()
  301.         );
  302.  
  303.         $rules = [
  304.             'token'        => 'required',
  305.             'email'        => 'required|valid_email',
  306.             'password'     => 'required|strong_password',
  307.             'pass_confirm' => 'required|matches[password]',
  308.         ];
  309.  
  310.         if (! $this->validate($rules)) {
  311.             return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
  312.         }
  313.  
  314.         $user = $users->where('email', $this->request->getPost('email'))
  315.             ->where('reset_hash', $this->request->getPost('token'))
  316.             ->first();
  317.  
  318.         if (null === $user) {
  319.             return redirect()->back()->with('error', lang('Auth.forgotNoUser'));
  320.         }
  321.  
  322.         // Reset token still valid?
  323.         if (! empty($user->reset_expires) && time() > $user->reset_expires->getTimestamp()) {
  324.             return redirect()->back()->withInput()->with('error', lang('Auth.resetTokenExpired'));
  325.         }
  326.  
  327.         // Success! Save the new password, and cleanup the reset hash.
  328.         $user->password         = $this->request->getPost('password');
  329.         $user->reset_hash       = null;
  330.         $user->reset_at         = date('Y-m-d H:i:s');
  331.         $user->reset_expires    = null;
  332.         $user->force_pass_reset = false;
  333.         $users->save($user);
  334.  
  335.         return redirect()->route('login')->with('message', lang('Auth.resetSuccess'));
  336.     }
  337.  
  338.     /**
  339.      * Activate account.
  340.      *
  341.      * @return mixed
  342.      */
  343.     public function activateAccount()
  344.     {
  345.         $users = model(UserModel::class);
  346.  
  347.         // First things first - log the activation attempt.
  348.         $users->logActivationAttempt(
  349.             $this->request->getGet('token'),
  350.             $this->request->getIPAddress(),
  351.             (string) $this->request->getUserAgent()
  352.         );
  353.  
  354.         $throttler = service('throttler');
  355.  
  356.         if ($throttler->check(md5($this->request->getIPAddress()), 2, MINUTE) === false) {
  357.             return service('response')->setStatusCode(429)->setBody(lang('Auth.tooManyRequests', [$throttler->getTokentime()]));
  358.         }
  359.  
  360.         $user = $users->where('activate_hash', $this->request->getGet('token'))
  361.             ->where('active', 0)
  362.             ->first();
  363.  
  364.         if (null === $user) {
  365.             return redirect()->route('login')->with('error', lang('Auth.activationNoUser'));
  366.         }
  367.  
  368.         $user->activate();
  369.  
  370.         $users->save($user);
  371.  
  372.         return redirect()->route('login')->with('message', lang('Auth.registerSuccess'));
  373.     }
  374.  
  375.     /**
  376.      * Resend activation account.
  377.      *
  378.      * @return mixed
  379.      */
  380.     public function resendActivateAccount()
  381.     {
  382.         if ($this->config->requireActivation === null) {
  383.             return redirect()->route('login');
  384.         }
  385.  
  386.         $login = $this->request->getGet('login');
  387.    
  388.         $throttler = service('throttler');
  389.    
  390.         if ($login == false) {
  391.             if ($throttler->check(md5($this->request->getIPAddress()), 2, MINUTE) === false) {
  392.                 return service('response')->setStatusCode(429)->setBody(lang('Auth.tooManyRequests', [$throttler->getTokentime()]));
  393.             }
  394.             $login = urldecode($this->request->getGet('login'));
  395.         }
  396.         $type  = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
  397.    
  398.         $users = model(UserModel::class);
  399.    
  400.         $user = $users->where($type, $login)
  401.             ->where('active', 0)
  402.             ->first();
  403.    
  404.         if (null === $user) {
  405.             return redirect()->route('login')->with('error', lang('Auth.activationNoUser'));
  406.         }
  407.    
  408.         $activator = service('activator');
  409.         $sent      = $activator->send($user);
  410.    
  411.         if (!$sent) {
  412.             return redirect()->back()->withInput()->with('error', $activator->error() ?? lang('Auth.unknownError'));
  413.         }
  414.    
  415.         // Success!
  416.         // return redirect()->route('login')->with('message', lang('Auth.activationSuccess'));
  417.         return redirect()->to('/data-pegawai')->with('berhasil', 'Email aktivasi berhasil terkirim');
  418.     }
  419.  
  420.     protected function _render(string $view, array $data = [])
  421.     {
  422.         return view($view, $data);
  423.     }
  424. }
  425.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement