I`m trying override "public function sendCode()" to use it in LoginController from below TokenModel.
have done more than tripled confirmed that loading and calling TokenModel from LoginController as an instance is succeed but "public function sendCode()" is not included with TokenModel.
would be very helpful if anyone knows what happens here and tell me what I should code.
=======================TokenModel=========================
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Token extends Model
{
const EXPIRATION_TIME = 15; // minutes
protected $fillable = [
'code',
'user_id',
'used'
];
public function __construct(array $attributes = [])
{
if (! isset($attributes['code'])) {
$attributes['code'] = $this->generateCode();
}
parent::__construct($attributes);
}
/**
* Generate a six digits code
*
* #param int $codeLength
* #return string
*/
public function generateCode($codeLength = 4)
{
$min = pow(10, $codeLength);
$max = $min * 10 - 1;
$code = mt_rand($min, $max);
return $code;
}
/**
* User tokens relation
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Send code to user
*
* #return bool
* #throws \Exception
*/
public function sendCode()
{
if (! $this->user) {
throw new \Exception("No user attached to this token.");
}
if (! $this->code) {
$this->code = $this->generateCode();
}
try {
app('twilio')->messages->create($this->user->getPhoneNumber(),
['from' => env('TWILIO_NUMBER'), 'body' => "Your verification code is {$this->code}"]);
} catch (\Exception $ex) {
return false; //enable to send SMS
}
return true;
}
/**
* True if the token is not used nor expired
*
* #return bool
*/
public function isValid()
{
return ! $this->isUsed() && ! $this->isExpired();
}
/**
* Is the current token used
*
* #return bool
*/
public function isUsed()
{
return $this->used;
}
/**
* Is the current token expired
*
* #return bool
*/
public function isExpired()
{
return $this->created_at->diffInMinutes(Carbon::now()) > static::EXPIRATION_TIME;
}
}
=======================LoginController=========================
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Token;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return mixed
*/
public function login(Request $request)
{
$this->validateLogin($request);
//retrieveByCredentials
if ($user = app('auth')->getProvider()->retrieveByCredentials($request->only('email', 'password'))) {
$token = Token::create([
'user_id' => $user->id
]);
if ($token->sendCode()) {
session()->set("token_id", $token->id);
session()->set("user_id", $user->id);
session()->set("remember", $request->get('remember'));
return redirect("code");
}
$token->delete();// delete token because it can't be sent
return redirect('/login')->withErrors([
"Unable to send verification code"
]);
}
return redirect()->back()
->withInputs()
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
/**
* Show second factor form
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
*/
public function showCodeForm()
{
if (! session()->has("token_id")) {
return redirect("login");
}
return view("auth.code");
}
/**
* Store and verify user second factor.
*/
public function storeCodeForm(Request $request)
{
// throttle for too many attempts
if (! session()->has("token_id", "user_id")) {
return redirect("login");
}
$token = Token::find(session()->get("token_id"));
if (! $token ||
! $token->isValid() ||
$request->code !== $token->code ||
(int)session()->get("user_id") !== $token->user->id
) {
return redirect("code")->withErrors(["Invalid token"]);
}
$token->used = true;
$token->save();
$this->guard()->login($token->user, session()->get('remember', false));
session()->forget('token_id', 'user_id', 'remember');
return redirect('home');
}
}
Related
I'm using Laravel 9 with the Laravel Spatie Permissions package. I have users and roles in my system. Users have roles, and depending on their permissions on their role they either can or can't create new users / new roles etc.
I've set up my UserPolicy and RolePolicy, and am passing my User model to each since it's the user that needs to be checked against what permissions they have, then in the controller of my choice, such as my RoleController I run:
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$this->authorize('viewAny', User::class);
$roles = Role::with('permissions')->get();
if (!$roles || count($roles) <= 0) {
return response()->json([
'message' => 'No roles found'
], 404);
}
return response()->json([
'roles' => $roles
], 200);
}
Strangely, if I edit my RolePolicy's viewAny permission and return false, I'm still able to see the data? I shouldn't be. what am I missing?
Here's my RolePolicy
<?php
namespace App\Policies\UserManagement;
use Spatie\Permission\Models\Role;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class RolePolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function viewAny(User $user)
{
// TODO: if I return false I still have access?
if ($user->can('role_index')) {
return true;
}
}
/**
* Determine whether the user can view the model.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function view(User $user)
{
if ($user->can('role_show')) {
return true;
}
}
/**
* Determine whether the user can create models.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function create(User $user)
{
if ($user->can('role_store')) {
return true;
}
}
/**
* Determine whether the user can update the model.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function update(User $user)
{
if ($user->can('role_update')) {
return true;
}
}
/**
* Determine whether the user can delete the model.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function delete(User $user)
{
if ($user->can('role_destroy')) {
return true;
}
}
}
And my AuthServiceProvider:
<?php
namespace App\Providers;
use App\Models\User;
use Spatie\Permission\Models\Role;
use App\Policies\UserManagement\UserPolicy;
use App\Policies\UserManagement\RolePolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* #var array<class-string, class-string>
*/
protected $policies = [
User::class => UserPolicy::class,
User::class => RolePolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
ResetPassword::createUrlUsing(function ($user, string $token) {
$frontendUrl = trim(rtrim(config('lespro.frontend_url'), '/'));
return $frontendUrl . '/account/reset/?email=' . $user->email . '&token=' . $token;
});
// Implicitly grant "super_admin" role all permissions
// This works in the app by using gate-related functions like auth()->user->can() and #can()
Gate::before(function ($user, $ability) {
return $user->hasRole('super_admin') ? true : null;
});
}
}
My policy for an API controller seems to be working fine for view, but returns 'This action is unauthorized.' for viewAll, both while sending an admin api token. Using Laravel 7 with Spatie Roles/Permissions. AppBaseController extends Illuminate\Routing\Controller. I've tried it without the middleware, just to be sure. Tried commenting out the 'before' function, to make sure it's not conflicting. Double-checked I'm sending Answer::class with the viewAny call. Confirmed the model 'can' method also returns false on viewAny. Tried it with and without optional User parameter in viewAny. Read and re-read the documentation, and every similar issue on here I could find. Can't seem to work out the issue. Not even sure how to trace what Laravel is doing to get that response.
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
//logged in
Route::group(['middleware' => ['auth:api', 'verified']], function () {
Route::get('answers', 'AnswerAPIController#index')->name('answers.index');
Route::post('answers/{id}', 'AnswerAPIController#store')->name('answers.store');
Route::get('answers/{id}', 'AnswerAPIController#show')->name('answers.show');
Route::put('answers/{id}', 'AnswerAPIController#update')->name('answers.update');
Route::delete('answers/{id}', 'AnswerAPIController#destroy')->name('answers.destroy');
});
AnswerPolicy.php
<?php
namespace App\Policies;
use App\Models\Answer;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class AnswerPolicy
{
use HandlesAuthorization;
/**
* Perform pre-authorization checks.
*
* #param \App\Models\User $user
* #param string $ability
* #return void|bool
*/
public function before(User $user, $ability)
{
if ($user->hasRole('admin')) {
return true;
}
}
/**
* Determine whether the user can view any answers.
*
* #param \App\Models\User $user
* #return mixed
*/
public function viewAny(User $user)
{
return true;
//
// if ($user !== null) {
// return true;
// }
}
/**
* Determine whether the user can view the answer.
*
* #param \App\Models\User|null $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function view(?User $user, Answer $answer)
{
return true;
// if ($answer->published) {
// return true;
// }
// visitors cannot view unpublished items
// if ($user === null) {
// return false;
// }
// // admin overrides published status
// if ($user->can('view answers')) {
// return true;
// }
}
/**
* Determine whether the user can create answers.
*
* #param \App\Models\User $user
* #return mixed
*/
public function create(User $user)
{
return true;
// if ($user->can('create answers')) {
// return true;
// }
}
/**
* Determine whether the user can update the answer.
*
* #param \App\Models\User $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function update(User $user, Answer $answer)
{
return true;
// if ($user->can('edit answers')) {
// return true;
// }
}
/**
* Determine whether the user can delete the answer.
*
* #param \App\Models\User $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function delete(User $user, Answer $answer)
{
return true;
// if ($user->can('delete answers')) {
// return $user->id == $answer->user_id;
// }
}
/**
* Determine whether the user can restore the answer.
*
* #param \App\Models\User $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function restore(User $user, Answer $answer)
{
return true;
//
}
/**
* Determine whether the user can permanently delete the answer.
*
* #param \App\Models\User $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function forceDelete(User $user, Answer $answer)
{
return true;
//
}
}
AnswerAPIController.php
<?php
namespace App\Http\Controllers\API;
use Auth;
use Log;
use Throwable;
use App\Http\Controllers\AppBaseController;
use App\Http\Requests\API\CreateAnswerAPIRequest;
use App\Http\Requests\API\UpdateAnswerAPIRequest;
use App\Repositories\AnswerRepository;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
/**
* Class AnswerController
* #package App\Http\Controllers\API
*/
class AnswerAPIController extends AppBaseController
{
use AuthorizesRequests;
/** #var AnswerRepository */
private $answerRepository;
public function __construct(AnswerRepository $answerRepo)
{
$this->answerRepository = $answerRepo;
}
/**
* #param Request $request
* #return Response
*/
public function index(Request $request)
{
try {
$this->authorize('viewAny', Answer::class);
$answers = $this->answerRepository->all(
$request->has('search') ? $request->get('search') : [],
$request->has('skip') && $request->has('limit') ? $request->get('skip') : null,
$request->has('limit') ? $request->get('limit') : null,
$request->has('columns') ? $request->get('columns') : ['*'],
$request->has('with') ? $request->get('with') : null,
$request->has('sort') ? $request->get('sort') : 'id',
$request->has('direction') ? $request->get('direction') : 'asc'
);
return $this->sendResponse($answers->toArray(), 'Answers retrieved successfully.');
} catch (Throwable $e) {
$trace = $e->getTrace()[array_search(__FILE__, array_column($e->getTrace(), 'file'))];
Log::error($e->getMessage() . " (" . $trace['file'] . ":" . $trace['line'] . ")\r\n" . '[stacktrace]' . "\r\n" . $e->getTraceAsString());
return $this->sendError($e->getMessage(), $request->all());
}
}
/**
* #param int $id
* #return Response
*/
public function show($id, Request $request)
{
try {
/** #var Answer $answer */
$answer = $this->answerRepository->find(
$id,
$request->has('columns') ? $request->get('columns') : ['*'],
$request->has('with') ? $request->get('with') : null
);
$this->authorize('view', $answer);
if (empty($answer)) {
return $this->sendError('Answer (' . $id . ') not found.');
}
return $this->sendResponse($answer->toArray(), 'Answer retrieved successfully.');
} catch (Throwable $e) {
$trace = $e->getTrace()[array_search(__FILE__, array_column($e->getTrace(), 'file'))];
Log::error($e->getMessage() . " (" . $trace['file'] . ":" . $trace['line'] . ")\r\n" . '[stacktrace]' . "\r\n" . $e->getTraceAsString());
return $this->sendError($e->getMessage());
}
}
}
request URL (index)
https://evenpulse.test/api/answers?api_token=****
response
{
"success": false,
"message": "This action is unauthorized.",
"data": {
"api_token": "****"
}
}
request URL (view)
https://evenpulse.test/api/answers/1?api_token=****
response
{
"success": true,
"data": {
"id": 1,
"question_id": 1,
"order": 1,
"text": "asdf",
"is_correct": false
},
"message": "Answer retrieved successfully."
}
In a classic case of 'asking often illuminates the problem', I figured it out 30 seconds later, after two days of struggles.
In the 'viewAny' authorize method I had put in the Answer::class bit, but nowhere in the controller did I define what 'Answer' is. I fixed it by adding
use App\Models\Answer;
to the top of the controller.
In my LoginController I have:
protected $redirectTo = '';
I then do this:
public function boot()
{
Parent::boot();
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
But in a method in the controller I check and I get a BLANK value from $this->redirectTo
protected function authenticated(Request $request, $user)
{
dd($this->redirectTo);
}
How do I make the value of this variable dynamic and use the route name to assign its value?
Here is my whole controller based on the comments below:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Which Authentication Guard we are working with
*
* #var string
*/
protected $guard = 'user';
/**
* URI where we redirect to after registration
*
* #var string
*/
protected $redirectTo = '';
/**
* URI where we redirect to after logout
*
* #var string
*/
protected $logoutTo = '';
/**
* LoginController constructor.
*/
public function __construct()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Parent::boot();
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('auth.user.main.login');
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
Auth::guard($this->guard)->logout();
$request->session()->flush();
$request->session()->regenerate();
if ($request->ajax()) {
return response()->json([
'type' => 'success',
'message' => trans('auth.logout_ok')
]);
} else {
return redirect($this->logoutTo ?: '/');
}
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
// If this user belongs to a partner
if ($user->isPartner()) {
// And the partner is active, then continue
if (!$user->partner->isActive()) {
// Else respond with an error
$error = [
'type' => 'error',
'message' => trans('messages.partner_inactive')
];
if ($request->ajax()) {
return response()->json($error);
} else {
return redirect()->back()->withErrors($error);
}
}
}
dd($this->redirectTo);
// Set up the user's session
$this->setupSession();
if ($request->ajax()) {
return response()->json([
'type' => 'success',
'user' => auth()->check(),
'intended' => $this->redirectPath(),
'message' => trans('auth.logout_ok')
]);
} else {
return redirect()->intended($this->redirectPath());
}
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($this->authenticated($request, $this->guard()->user())) {
return true;
} else {
if ($request->ajax()) {
return response()->json([
'type' => 'error',
'user' => auth()->check(),
'intended' => $this->redirectPath(),
'message' => trans('auth.not_login')
]);
} else {
return redirect()->intended($this->redirectPath());
}
}
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* Set up all session variables here
*/
private function setupSession()
{
// session()->put('user', Auth::user());
}
}
I had to put my assignments here
public function __construct()
{
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
I am trying to integrate the auth in laravel 5.4 within an existing database where the user and password fields have other names (memberid, passwordnew_enc). With the bellow changes and forcing the create function in RegisterController to use MD5 I managed to make the registration work. It also logins fine after registration. However the actual login form returns:
These credentials do not match our records.
So far I have changed the User.php
public function getAuthPassword()
{
return $this->passwordnew_enc;
}
and
public function setPasswordAttribute($value)
{
$this->attributes['password'] = md5($value);
}
Also on LoginController.php
public function username()
{
return 'memberid';
}
Did I miss something ?
I only need to change the two column names to fit and the password encryption from bcrypt to md5
I would make custom user provider php artisan make:provider CustomUserProvider:
<?php
namespace App\Providers;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
class CustomUserProvider extends EloquentUserProvider {
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password']; // will depend on the name of the input on the login form
$hashedValue = $user->getAuthPassword();
if ($this->hasher->needsRehash($hashedValue) && $hashedValue === md5($plain)) {
$user->passwordnew_enc = bcrypt($plain);
$user->save();
}
return $this->hasher->check($plain, $user->getAuthPassword());
}
}
This way if the password exists using md5 it will allow it to work once and then rehash it.
You will register the CustomUserProvider in App\Providers\AuthServiceProvider boot() as follows:
$this->app['auth']->provider('custom', function ($app, array $config) {
$model = $app['config']['auth.providers.users.model'];
return new CustomUserProvider($app['hash'], $model);
});
Edit your config/auth.php
'providers' => [
'users' => [
'driver' => 'custom',
'model' => App\User::class,
],
],
You will also need to add the following as mentioned previously...
app\Http\Controllers\Auth\LoginController.php
public function username()
{
return 'memberid';
}
app\User.php
public function getAuthIdentifierName()
{
return 'memberid';
}
public function getAuthIdentifier()
{
return $this->memberid;
}
public function getAuthPassword()
{
return $this->passwordnew_enc;
}
Alright I got it
app\User.php
public function setPasswordAttribute($value)
{
$this->attributes['password'] = md5($value);
}
public function getAuthPassword()
{
return $this->passwordnew_enc;
}
public function getAuthIdentifierName()
{
return 'memberid';
}
app\Http\Controllers\Auth\LoginController.php
public function username()
{
return 'memb___id';
}
config\app.php
// Illuminate\Hashing\HashServiceProvider::class,
App\Providers\MD5HashServiceProvider::class,
app\Providers\MD5HashServiceProvider.php
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class MD5HashServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* #var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$this->app->singleton('hash', function () {
return new \MD5Hasher;
});
}
/**
* Get the services provided by the provider.
*
* #return array
*/
public function provides()
{
return ['hash'];
}
}
lib\MD5Hasher\MD5Hasher.php
<?php
class MD5Hasher implements Illuminate\Contracts\Hashing\Hasher
{
/**
* Hash the given value.
*
* #param string $value
* #return array $options
* #return string
*/
public function make($value, array $options = array())
{
return md5($value); //hash('md5', $value);
}
/**
* Check the given plain value against a hash.
*
* #param string $value
* #param string $hashedValue
* #param array $options
* #return bool
*/
public function check($value, $hashedValue, array $options = array())
{
return $this->make($value) === $hashedValue;
}
/**
* Check if the given hash has been hashed using the given options.
*
* #param string $hashedValue
* #param array $options
* #return bool
*/
public function needsRehash($hashedValue, array $options = array())
{
return false;
}
}
composer.json
...
"autoload": {
"classmap": [
...
"app/Lib"
],
...
upful's code worked for me (in Laravel 5.4)
But I needed to add:
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
in the CustomUserProvider class.
Today i came across with a probleme in Yii2 Authentication. I implemented succesfully but when i try to log in every time it shows me the following error:
After i refresh the page 1 or 2 times the error goes off and everything works properly. My first tought was to add the database field auth_key (32) varchar but it didn't solved the issue.
Here is my User.php:
<?php
namespace app\models;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements \yii\web\IdentityInterface
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'felhasznalo';
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByFelhasznalonev($felhasznalonev)
{
return static::findOne(['felhasznalonev' => $felhasznalonev]);
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->auth_Key;
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->auth_Key === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->jelszo === sha1($password);
}
}
The login action:
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
if (empty($_SESSION['ablak_id'])) {
$_SESSION['ablak_id'] = Yii::$app->request->post('a_id');
}
else {
return $this->redirect(Url::to(['ugyfelhivo/muszerfal/' . $_SESSION['ablak_id']]));
}
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$session = Yii::$app->session;
$session->set('ablak_id', Yii::$app->request->post('ablak_id'));
return $this->redirect(Url::to(['ugyfelhivo/muszerfal/' . $_SESSION['ablak_id']]));
}
//Lekérdezzük az elérhető rendelők nevét majde elküldjük kimenetre
$ablakok = Ablak::find()->all();
return $this->render('login', [
'model' => $model,
'ablakok' => $ablakok,
]);
}
And the LoginForm.php:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* #param string $attribute the attribute currently being validated
* #param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByFelhasznalonev($this->username);
}
return $this->_user;
}
}
This is the table structure for the users table(felhasznalok == users in hungary)
Any ideas for the problem?
Thank your for Your answers!
Gábor
It is simply a typo, you should use auth_key instead of auth_Key :
public function validateAuthKey($authKey)
{
return $this->auth_key === $authKey;
}
try changing the getUser function in your LoginForm into:
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByFelhasznalonev($this->username);
//generate auth_key for a new created User
$this->_user->generateAuthKey();
}
return $this->_user;
}