Where do i override authentication method in yii? - yii

I need to override both authentication (for when user's trying to logging in) and also the function is being used to check if the user is logged in in the header of the application (the function that check the sessions and cookie to check if the user is logged in) but i don't know where are these methods? and also i don't know how to find where are these methods!
** The reason of ovveride is to also check a Flag, if the flag is FLASE don't authenticate the user, or even if the user is also authenticated on page change (header reload) log-out the user if the flag changed to FLASE**
It would be appreciated if you also helping me to find adequate references that can help me in similar situations beside yii/wiki and google i tried them :)
Regards,

For custom authentication extend CUserIdentity class:
app/components/UserIdentity.php
<?php
class UserIdentity extends CUserIdentity
{
const ERROR_USER_NOT_APPOVED=200;
private $_id;
/**
* Authenticates a user.
*
* #return boolean whether authentication succeeds.
*/
public function authenticate()
{
$criteria = new CDbCriteria;
$criteria->condition = 'LOWER(email.email)=LOWER(:email)';
$criteria->params = array(':email' => $this->username);
$member = Member::model()
->with('email')
->together()
->find($criteria);
if ($member === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
} elseif (!hash::check($this->password, $member->pass_hash)) {
$this->errorCode = self::ERROR_PASSWORD_INVALID;
} elseif (! $member->is_approved) {
$this->errorCode = self::ERROR_USER_NOT_APPOVED;
} else {
$this->_id = $member->id;
$this->username = $member->full_name;
$this->setState('email', $member->email->email);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
/**
* #return integer the ID of the user record
*/
public function getId()
{
return $this->_id;
}
}
then create custom form (app/models/MainLoginForm.php):
<?php
/**
* MainLoginForm class.
* MainLoginForm is the data structure for keeping
* user login form data.
*/
class MainLoginForm extends CFormModel
{
public $email;
public $password;
public $rememberMe;
/**
* Declares the validation rules.
* The rules state that email and password are required,
* and password needs to be authenticated.
*/
public function rules()
{
return array(
array('email', 'filter', 'filter' => 'trim'),
array('email', 'required',
'message' => Yii::t('auth', 'Email address is required.')),
array('email', 'email',
'message' => Yii::t('auth', 'Enter a valid Email address.')),
array('password', 'required',
'message' => Yii::t('auth', 'Password is required.')),
// password needs to be authenticated
array('password', 'authenticate'),
array('rememberMe', 'safe'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'email' => Yii::t('auth', 'Email Address'),
'password' => Yii::t('auth', 'Password'),
'rememberMe' => Yii::t('auth', 'Remember me.'),
);
}
/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute, $params)
{
// we only want to authenticate when no input errors
if (! $this->hasErrors()) {
$identity = new UserIdentity($this->email, $this->password);
$identity->authenticate();
switch ($identity->errorCode) {
case UserIdentity::ERROR_NONE:
$duration = ($this->rememberMe)
? 3600*24*14 // 14 days
: 0; // login till the user closes the browser
Yii::app()->user->login($identity, $duration);
break;
default:
// UserIdentity::ERROR_USERNAME_INVALID
// UserIdentity::ERROR_PASSWORD_INVALID
// UserIdentity::ERROR_MEMBER_NOT_APPOVED
$this->addError('', Yii::t('auth',
'Incorrect username/password combination.'));
break;
}
}
}
}
and finally update your login method (actionLogin):
$form = new MainLoginForm;
if (isset($_POST['MainLoginForm'])) {
$form->attributes = $_POST['MainLoginForm'];
$valid = $form->validate();
if ($valid) {
// redirect
}
}
For auto logout you can extend CController:
app/components/MainBaseController.php
<?php
class MainBaseController extends CController
{
public $settings = array();
public function init()
{
parent::init();
// set global settings
// $this->settings = ...
if (YOUR_FLAG_VALIDATION AND !Yii::app()->user->isGuest) {
Yii::app()->user->logout();
}
}
}
and then use custom base controll:
class YourController extends MainBaseController
{
....
}

Related

Symfony 5 / login-signin / Guard authentication

I have to use LoginForm and RegistrationForm in the same page
I m using classic Guard Authentication provided by make:auth
Based on Symfony 5 - Multiples forms on same page, I have created LoginFormType and copy what I have in RegistrationController.
Both Login and Registration fails.
security.yaml :
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
lazy: true
provider: app_user_provider
guard:
authenticators:
- App\Security\LoginFormAuthenticator
logout:
path: app_logout
target: app_login
remember_me:
secret: '%kernel.secret%'
lifetime: 604800 # 1 week in seconds
path: /
Security/LoginFormAuthenticator.php
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface{
use TargetPathTrait;
public const LOGIN_ROUTE = 'app_login';
/**
* #var $entityManager EntityManagerInterface
*/
private $entityManager;
/**
* #var UrlGeneratorInterface
*/
private $urlGenerator;
/**
* #var $csrfTokenManager CsrfTokenManagerInterface
*/
private $csrfTokenManager;
/**
* #var $passwordEncoder UserPasswordEncoderInterface
*/
private $passwordEncoder;
public function __construct(
EntityManagerInterface $entityManager,
UrlGeneratorInterface $urlGenerator,
CsrfTokenManagerInterface $csrfTokenManager,
UserPasswordEncoderInterface $passwordEncoder
) {
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
}
public function supports(Request $request)
{
return self::LOGIN_ROUTE === $request->attributes->get('_route')
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'email' => $request->request->get('email'),
'password' => $request->request->get('password'),
'csrf_token' => $request->request->get('_csrf_token'),
];
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['email']
);
return $credentials;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = new CsrfToken('authenticate', $credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token)) {
throw new InvalidCsrfTokenException();
}
$user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Email could not be found.');
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function getPassword($credentials): ?string
{
return $credentials['password'];
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
dd('hello');
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new RedirectResponse($targetPath);
}
return new RedirectResponse($this->urlGenerator->generate('dashboard'));
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}
SecurityController login method
public function login(
Request $request,
AuthenticationUtils $authenticationUtils,
GuardAuthenticatorHandler $guardAuthenticatorHandler,
LoginFormAuthenticator $loginFormAuthenticator
): Response {
if ($this->getUser()) {
return $this->redirectToRoute('dashboard');
}
// LOGIN
$userToLogIn = new User();
$director = new Director();
$loginForm = $this->createForm(LoginFormType::class, $userToLogIn);
$registrationForm = $this->createForm(RegistrationFormType::class, $director);
if ($request->isMethod(Request::METHOD_POST)) {
$loginForm->handleRequest($request);
$registrationForm->handleRequest($request);
dump($request->get('signIn'));
dd($request->get('signUp'));
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'loginForm' => $loginForm->createView(),
'registrationForm' => $registrationForm->createView()
]);
}
I m using:
Symfony 5.1.3
PHP 7.3.20 ( I m not upgraded to 7.4 yet for non compatibility of some vendors)
I m using Symfony local server, no nginx or apache
I don't have any .htaccess file
When I m googling that, I found that could be relative to session, that's why I added
framework.yaml :
framework:
//...
session:
//...
save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
Login and registration worked before separately
But now when I just visit any page in my site
I have this
and This when I try to login
Any Help please ???
I solved the problem by rendering the registration controller in the login template
login.html.twig
// login form
....
{{ render(controller('App\\Controller\\RegistrationController::register')) }}

How to enable email verification link to expire after verification in laravel 6 API implemented using VerifiesEmail feature?

I have implemented Laravel 6 API and used Laravel's inbuilt Illuminate\Foundation\Auth\VerifiesEmails based on tutorial here but the email verification link is not expired and still accessible after successful email verification. I have found many tutorials regarding laravel frontend but how to implement it on API.
VerificationApiController
class VerificationApiController extends Controller
{
use VerifiesEmails;
/**
* Mark the authenticated user's email address as verified.
* #param Request $request
* #return JsonResponse
*/
public function verify(Request $request): JsonResponse
{
$userID = $request['id'];
$user = User::findOrFail($userID);
$date = date('Y-m-d g:i:s');
// to enable the “email_verified_at field of that
// user be a current time stamp by mimicking the
// must verify email feature
$user->email_verified_at = $date;
$user->save();
return response()->json('Email verified!');
}
/**
* Resend the email verification notification.
* #param Request $request
* #return JsonResponse|Response
*/
public function resend(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return response()->json('User already have verified email!', 422);
}
$request->user()->sendEmailVerificationNotification();
return response()->json('The notification has been resubmitted');
// return back()->with(‘resent’, true);
}
}
User model
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, Notifiable;
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Send email verification notification
*/
public function sendApiEmailVerificationNotification()
{
$this->notify(new VerifyApiEmail); // my notification
}
}
Here are verification api routes
Route::get(‘email/verify/{id}’, ‘VerificationApiController#verify’)->name(‘verificationapi.verify’);
Route::get(‘email/resend’, ‘VerificationApiController#resend’)->name(‘verificationapi.resend’)
Here is UsersApiController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
use Auth;
use Validator;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Auth\Events\Verified;
class UsersApiController extends Controller
{
use VerifiesEmails;
public $successStatus = 200;
/**
* login api
*
* #return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt([‘email’ => request(‘email’), ‘password’ => request(‘password’)])){
$user = Auth::user();
if($user->email_verified_at !== NULL){
$success[‘message’] = “Login successfull”;
return response()->json([‘success’ => $success], $this-> successStatus);
}else{
return response()->json([‘error’=>’Please Verify Email’], 401);
}
}
else{
return response()->json([‘error’=>’Unauthorised’], 401);
}
}
/**
* Register api
*
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
‘name’ => ‘required’,
‘email’ => ‘required|email’,
‘password’ => ‘required’,
‘c_password’ => ‘required|same:password’,
]);
if ($validator->fails()) {
return response()->json([‘error’=>$validator->errors()], 401);
}
$input = $request->all();
$input[‘password’] = Hash::make($input[‘password’]);
$user = User::create($input);
$user->sendApiEmailVerificationNotification();
$success[‘message’] = ‘Please confirm yourself by clicking on verify user button sent to you on your email’;
return response()->json([‘success’=>$success], $this-> successStatus);
}
/**
* details api
*
* #return \Illuminate\Http\Response
*/
public function details()
{
$user = Auth::user();
return response()->json([‘success’ => $user], $this-> successStatus);
}
}
Here are user and auth routes
Route::post(‘login’, ‘UsersApiController#login’);
Route::post(‘register’, ‘UsersApiController#register’);
Route::group([‘middleware’ => ‘auth:api’], function(){
Route::post(‘details’, ‘UsersApiController#details’)->middleware(‘verified’);
}); // will work only when user has verified the email
so the problem is that when I click on verification link on email the user is verified but the link is not expired . I want the link to be expired as soon as user is verified. How to do that?
Have you implemented the VerifyApiEmail class?
namespace App\Notifications;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;
class VerifyApiEmail extends VerifyEmailBase
{
protected function verificationUrl($notifiable)
{
return URL::temporarySignedRoute(
'api.auth.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
);
}
}
Here you can add the expiration time in minutes, seconds or hours.

Laravel not inserting into table

Basically I need to have a e-mail verification system. For clarity, I will post only needed chunks of code that have impact whatsoever. When user registers, a random 40 string token is generated and sent to them, that code is appended to the route like this:
Route::get('/user/verify/{token}', 'RegisterController#verifyUser');
So when user clicks on that link supposedly route should call this:
RegisterController:
public function verifyUser($token){
$verifyUser = new VerifyUser();
$verifyUser->token = $token;
$verifyUser->getByToken();
$user = new User();
$user->id = $verifyUser->user_id;
$user->get();
if(isset($verifyUser)){
if(!$user->verified){
$user->updateVerifiedStatus();
$status = "Uspešno ste verifikovali e-mail adresu. Sada se možete ulogovati";
} else{
$status = "Već ste se verifikovali.";
}
} else{
return redirect('/')->with('error', "Vaš e-mail ne postoji");
}
return redirect('/')->with('status', $status);
}
verify_user is table which has an id of the user, and the token field, and if user is not registered, there will be no instance of that user in the table, therefore -> if(isset($verifyUser)),
also, user table has an 'verified' field, which is a boolean and stores true and false values, therefore -> if(!$user->verified).
And here are models which are used in the above mentioned controller
VerifyUser:
class VerifyUser
{
public $user_id;
public $token;
public $created_at;
public $updated_at;
public function getByToken()
{
$result =
DB::table('verify_users')
->select('*')
->where('token', $this->token)
->first();
return $result;
}
public function create()
{
$result =
DB::table('verify_users')
->insert([
'user_id' => $this->user_id,
'token' => $this->token,
]);
return $result;
}
}
User
class User
{
public function get()
{
$result =
DB::table('users')
->select('*')
->where('id', $this->id)
->first();
return $result;
}
public function updateVerifiedStatus()
{
$data = [
'verified' => true,
];
$result =
DB::table('users')
->where('id', $this->id)
->update($data);
return $result;
}
}
So, when I click the link, everything passess, I get the success status, which tells me that $user->updateVerifiedStatus() funct is returned succesfully. But, when I check the table, the field is still false, and is not updated. Any ideas?

Yii Authentication and Authorization

I followed steps in this article http://www.yiiframework.com/doc/guide/1.1/en/topics.auth how create login and registration system on my site, but I don't understand where should I put this code, in what file??
$identity=new UserIdentity($username,$password);
if($identity->authenticate())
Yii::app()->user->login($identity);
else
echo $identity->errorMessage;
......
// Logout the current user
Yii::app()->user->logout();
first you should create a LoginForm like this.
<?php
/**
* LoginForm class.
* LoginForm is the data structure for keeping
* user login form data. It is used by the 'login' action of 'SiteController'.
*/
class LoginForm extends CFormModel {
public $username;
public $password;
public $rememberMe;
public $qrcode;
private $_identity;
/**
* Declares the validation rules.
* The rules state that username and password are required,
* and password needs to be authenticated.
*/
public function rules() {
return array(
// username and password are required
array('username, password', 'required'),
// rememberMe needs to be a boolean
array('rememberMe', 'boolean'),
// password needs to be authenticated
array('password', 'authenticate'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels() {
return array(
//'rememberMe'=>'Remember me next time',
'rememberMe' => Yii::t('default', 'Remember me next time'),
'username' => Yii::t('default', 'Username'),
'password' => Yii::t('default', 'Password'),
);
}
/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute, $params) {
if (!$this->hasErrors()) {
$this->_identity = new UserIdentity($this->username, $this->password);
if (!$this->_identity->authenticate())
$this->addError('password', Yii::t('default', 'Incorrect username or password'));
}
}
/**
* Logs in the user using the given username and password in the model.
* #return boolean whether login is successful
*/
public function login() {
if ($this->_identity === null) {
$this->_identity = new UserIdentity($this->username, $this->password);
// Yii::app()->user->setState("password", $this->password);
//$_SESSION['password'] = $this->password;
$this->_identity->authenticate();
}
if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
$duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days
Yii::app()->user->login($this->_identity, $duration);
return true;
} else
return false;
}
}
second create file UserIdentity like this.
<?php
/**  * UserIdentity represents the data needed to identity a user.
* * It contains the authentication method that checks if the provided
* * data can identity the user.
*/
class UserIdentity extends CUserIdentity {
private $_id;
public $user;
public $usertype;
public function authenticate() {
$user = User::model()->find('LOWER(username)=? or easiio_id=?', array(strtolower($this->username), $this->username));
if ($user === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
} else {
//date_default_timezone_set("America/Los_angeles");
$this->_id = $user->id;
$this->usertype = $user->status;
$this->user = $user;
$this->username = $user->username;
$this->setState("user", $user);
$this->setState('username', $user->username);
$this->setState('password', $user->password);
$this->setState('org', $user->org_id);
$user->saveAttributes(array(
'lastlogin' => date("Y-m-d H:i:s", time()),
));
$this->errorCode = self::ERROR_NONE;
}
return $this->errorCode == self::ERROR_NONE;
}
public function getId() {
return $this->_id;
}
}
third login

Laravel Auth::check() only returns true on post page

I am new at Laravel and having some struggles with simple login and authorization pages.
I followed an awesome video tutorial by laracasts.com (credits for that one, really helpful).
My situation:
When implementing authorization to my page, the page after the login succeeds the authorization check.
So: loginform > press button > You are now logged in.
My problem:
After I press the back button and refresh, it still gives the login form. It shouldn't.
routes.php
<?php
Route::get('login', 'SessionsController#create');
Route::get('logout', 'SessionsController#destroy');
Route::resource('users', 'UsersController');
Route::resource('sessions', 'SessionsController');
Route::get('admin', function(){
return 'Admin page';
})->before('auth');
Route::get('dashboard', ['before' => 'auth', function(){
return 'Dashboard';
}]);
SessionsController.php:
<?php
class SessionsController extends BaseController{
public function create()
{
if ( Auth::check() )
{
Redirect::to('/admin');
}
return View::make('sessions.create');
}
public function store()
{
if( Auth::attempt(Input::only('email', 'password')) )
{
// if(Auth::check())
// {
// return 'check worked!';
// }
return 'Welcome ' . Auth::user()->username; //You are now logged in
}
return 'Failed';
}
public function destroy()
{
Auth::logout();
return Redirect::to('sessions.create');
}
}
User.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public $timestamps = true;
protected $fillable = ['username', 'email', 'password'];
protected $guarded = ['id'];
public static $rules = [
'username' => 'required',
'password' => 'required'
];
public $errors;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function isValid()
{
$validation = Validator::make($this->attributes, static::$rules );
if($validation->passes() )
return true;
$this->errors = $validation->messages();
return false;
}
}
create.blade.php
#extends('layouts.default')
#section('content')
<h1>Create new user</h1>
{{Form::open([ 'route' => 'users.store' ]) }}
<div>
{{Form::label('username', 'Username: ')}}
{{Form::text('username')}}
{{$errors->first('username')}}
</div>
<div>
{{Form::label('password', 'Password: ')}}
{{Form::password('password')}}
{{$errors->first('password')}}
</div>
<div>
{{Form::submit('Create User')}}
</div>
{{Form::close() }}
#stop
So to speak: It never goes to the 'admin' route.
Your authentication code is correct and working. What you have is something going wrong in any other part of your Laravel application, web server or even PHP.
Since we are not seeing all your code, we can just guess, so my first one would be the Session not being stored correctly. Currently logged users are stored in Laravel Session. So, check your session driver, if it's in 'native', change it to 'database', but you'll have to create a sessions table, look at the docs. If you are already using 'database', change it back to 'native' or even 'file'.
Instead of run
return 'Welcome ' . Auth::user()->username; //You are now logged in
Please try
return Redirect::to('admin');