Yii2. Authorised users list - session

I've used standard yii2 functions for authorization. User sessions are stored in database.
How can I get the list of all authorized users in Yii2?

Use this code:
$sessions = (new Query())->select('*')->from('session')->where('expire > :now', [
':now' => time()
])->all();
foreach($sessions as $session) {
$sessionData = Yii::$app->session->readSession($session['id']);
$sessionUnserializedData = $this->unserialize_session($sessionData);
$userId = $sessionUnserializedData['__id'];
echo $userId;
}
unserialize_session method get from #phred gist.

Related

Laravel login without register

Is it possible to login a user in Laravel 7 without having the user on the database? I have a group of users, which I don't want them on my database, because they use an external API to do the login and I can get their details from that API (via XML).
There are 3 types of users:
AR division users. Normal registered users.
Non-AR division users, but $user->gca = 1. Registered users too.
Non-AR division and Non-GCA users. Non-registered users.
All of them use an external API for the login. However, I only register the first 2 ones on my database for organisational purposes.
My intention is to use Laravel login using the 3rd type user details from the API without touching my database.
My code at LoginController.php
$user_array = json_decode(file_get_contents($this->api_url . '?type=json&token=' . $request->cookie($this->cookie_name)));
if ($user_array->result)
{
$u = NULL;
if ($user = User::find($user_array->vid)) $u = $user;
else if($user_array->division == 'AR' || !is_null(Gca::find($user_array->vid)))
{
$u = new User();
if(! is_null(Gca::find($user_array->vid))) $u->gca = 1;
$u->name = $user_array->firstname;
$u->vid = $user_array->vid;
$vid = $u->vid;
$u->save();
return view('register', compact('vid'));
}
else
{
$user = new User();
$user->division = $user_array->division;
$user->vid = $user_array->vid;
$user->name = $user_array->firstname;
$user->surname = $user_array->lastname;
Auth::login($user); //This doesn't seem to work.
return redirect('/');
}
}
Thanks.

How to get access to authorized user from api inside laravel eloquent model?

I have custom attribute which I must show only authorized users with specific roles:
protected $appends = ['count'];
public function getCountAttribute()
{
$user = auth()->guard('api')->user();
if($user && $user->hasAnyRole(['company', 'editor'])) {
$unmoderated = $this->jobs()->where('status', 0)->count();
$active = $this->jobs()->where('status', 1)->count();
$closed = $this->jobs()->where('status', 2)->count();
return [
'all' => $unmoderated + $active + $closed,
'unmoderated' => $unmoderated,
'active' => $active,
'closed' => $closed
];
}
}
This code every time return null on result. Because can't see authorized user from API with Laravel Passport. By default from controllers we can access to authorized user from API by adding middleware:
->middleware('auth:api')
But how I can do it inside model?
you can directly pass guard in helper method
$user = auth('api')->user();
Or Facade
use Illuminate\Support\Facades\Auth;
Auth::guard('api')->user();

Laravel - Check if user is authenticated on another server

Let say I have a laravel site on a host and another host just for storing some specific files. In second host I want to check if user is authenticated on laravel site and then I gave him/her access to the file. How can I do this?
You could pretty much just use normal PHP code for that, without having to touch the Laravel framework on your other server.
For example, create your own custom cookie or session variable that contains a token from authentication. Make the logic something like $authToken = md5($user->username) . "." . md5($user->password);, then just add it to a cookie or the $_SESSION[] variable.
From here, create a small backend on the other server that you use for storage, and do something like this.
<?php
/////////////
/**
* Here there should be database connection logic.
*/
/////////////
$posts = (object) $_POST;
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$postArray = [
'authToken',
'user'
];
foreach($postArray as $post)
{
if (!isset($_POST[$post]))
{
return false;
}
}
$query = htmlspecialchars("SELECT * FROM users WHERE id=" . $posts->user);
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_all($result);
$db_stack = md5($row['username']) . "." . md5($row['password']);
if ($posts->authToken != $db_stack)
{
return false;
}
// Return the requested file here.
}
If (Auth::check()) $file = file_get_contents($urlToFile);

redirect to admin and user based on user role in code igniter

If the admin is logging in. I want him to go to admin/dashboard. otherwise to the users dashboard. The controller of login is follow. In the users table, I have a column of 'role' and the value are '1' and '2'. 1 stands for admin and 2 for user. and there is separate table for role.
Login User function
public function login(){
$data['title'] = 'Login';
//validating form
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() ===FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}else{
//Get username
$username = $this->input->post('username');
//Get password in md5
$password= md5($this->input->post('password'));
//Login User.... passing username and password
$user_id = $this->user_model->login($username, $password);
//checking userid
if($user_id){
//creating session if user_id is present
$user_data=array(
'user_id'=>$user_id,
'username'=>$username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata('user_loggedin', 'Login successful');
redirect('posts');
}else{
//creating session if user_id is not present
$this->session->set_flashdata('login_failed', ' Invalid credentials');
redirect('users/login');
}
}
}
while validating the user, you have to send an array as a response to login call.
$user_info = $this->user_model->login($username, $password); // User Info should be an Array $user_info = array('user_id' => '123', 'role' => '1'); if exist and $user_info = array(); if not
if(isset($user_info['user_id']) && !empty($user_info['user_id'])) {
$user_data=array(
'user_id'=>$user_info['user_id'],
'username'=>$username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
$this->session->set_flashdata('user_loggedin', 'Login successful');
if($user_info['role'] == 1){
redirect('admin/dashboard');
} else {
redirect('user/dashboard');
}
}
Sure this will help you.
I don't know exactly the column name what you set for user role. Say this is user_role_id and here is my example for you.
//checking userid
if($user_id){
//creating session if user_id is present
$user_data=array(
'user_id'=>$user_id, // you should change this variable to $user_id['id']
'username'=>$username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata('user_loggedin', 'Login successful');
if($user_id['user_role_id'] == 1){
redirect('admin/dashboard', 'refresh');
}
else if($user_id['user_role_id'] == 2){
redirect('users/dashboard', 'refresh');
}
}else{
//creating session if user_id is not present
$this->session->set_flashdata('login_failed', ' Invalid credentials');
redirect('users/login');
}
The main developer of the contemporary CodeIgniter , Mr Lonnie Ezell
in this post on the CodeIgniter's forum,
https://forum.codeigniter.com/thread-67063-post-339924.html#pid339924
explains the use of CodeIgniter filters
http://codeigniter.com/user_guide/incoming/filters.html
Please , pay attention to and kindly note the example he does
Thinking about who writes the post...
you have the correct CodeIgniter's approach for the users and admins accessibility delimitations
So let's create your filter in /App/Filters by copying the skeleton you find in the documentation #
https://codeigniter.com/user_guide/incoming/filters.html#creating-a-filter
e.g. save it as /App/Filters/AccessFilter.php
customize the name according with your needs and fill the before method with your is-logged-in check and redirect action if not logged in
then go to the Filters configuration setup in /App/Config/Filters.php and
assign your brand new created filter an alias name
'accessCheck' => \App\Filters\AccessFilter::class
select the policy that best fits your need, e.g. the bottom one in the Filters.php config file and note the provided hint that comes with the default CodeIgniter installation it tells
/* List filter aliases and any before/after uri patterns that they should run on, like: 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']], */
well so let's use it
public $filters = [
'accessCheck' => ['before' => ['controllerName(/*)?']]
];
where controllerName is the controller you want to deny access if the user is not logged in
please note that you can deny multiple controllers as array and also note that the regex condition will stop the access to every method of the controller including the index() one
so it will stop both
site_url("/controllerName")
site_url("/controllerName/*")
Bonus:
Also note that filters can be set in the custom routes strings as parameters
https://codeigniter.com/user_guide/incoming/routing.html#applying-filters
( this selective use, will allow to e.g. avoid already logged in users to access the login page or the sign up page and other similar "deviations" )

laravel login with google account

I am making an application and I want users to login with their google account. I have user oauth-4-laravel and I have this:
UserController.php
// get data from input
$code = Input::get('code');
// get google service
$googleService = Artdarek\OAuth\Facade\OAuth::consumer("Google");
if (!empty($code)) {
// This was a callback request from google, get the token
$token = $googleService->requestAccessToken($code);
// Send a request with it
$result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
$user = DB::select('select id from users where email = ?', array($result['email']));
if (empty($user)) {
$data = new User;
$data->Username = $result['name'];
$data->email = $result['email'];
$data->first_name = $result['given_name'];
$data->last_name = $result['family_name'];
$data->save();
}
if (Auth::attempt(array('email' => $result['email']))) {
return Redirect::to('/');
} else {
echo 'error';
}
}
// if not ask for permission first
else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to facebook login url
return Redirect::to((string) $url);
}
}
After this i get successfully user info and can save user name, in my database. The problem is that after this I want to redirect user to home page and can't do this because with normal login i chec authentication:
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
and with google login i get onlu username , user id and email. How to login directly the user after google login?
If you need to log an existing user instance into your application, you may simply call the login method with the instance:
$user = User::find(1);
Auth::login($user);
This is equivalent to logging in a user via credentials using the attempt method.
For further info see: http://laravel.com/docs/security#manually

Resources