I'm new to phalcon and i used to learn invo example application. In security.php i found :
$auth = $this->session->get('auth');
if (!$auth){
$role = 'Guests';
} else {
$role = 'Users';
}
are there any way to create user group with different assigned role like joomla?
Thanks
What you can do is, when the user logs in set the session as follows :-
$this->session->set('auth', array(
'username' => $user->username,
'power' => $user->power //Assuming that you have power assigned to each user
));
Now when you need to check the user's role you can implement the following method :-
$auth = $this->session->get('auth');
if(!$auth) {
$role = 'Guest';
} elseif($auth['power'] == 0) {
$role = 'Admin';
} elseif($auth['power'] == 2) {
$role = 'Sub-Admin';
} else {
$role = 'User'; //If power equals to 1 or 2 then assign the role else assign normal user role
}
I hope this helps.
Related
The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.
I have many attributes for the users' table. Admin needs to register a new user. My question is how to log in only with email and password?. my code now when user login user will get this error and this users database table . I only want to insert email and password when login in.
Controller\Auth\AuthController.php
public function login(Request $request)
{
if (!\Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->back();
} else {
return view('layouts.admin');
}
}
Http\UserController.php
public function store(Request $request)
{
$user = new User();
$user->Id_staff = $request['Id_staff'];
$user->name = $request['name'];
$user->noIc = $request['noIc'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->pusat_tangungjawab = $request['pusat_tangungjawab'];
$user->jawatan = $request['jawatan'];
$user->user_group = $request['user_group'];
$user->user_level = $request['user_level'];
$user->phone_no = $request['phone_no'];
$user->save();
return redirect()->route('users.index');
}
If you create a migration for users table, maybe the reason for that error because you didn't set nullable for Id_staff. So if you create a user and didn't post a value of Id_staff you will get that error. Some solutions is set a default value by random or set nullable in your migration, for example:
$table->string('Id_staff')->nullable();
I want to get Auth ID from user who has logged in and then use the Auth ID to store on other table
User_detail Controller
this is my store function
$data = new ModelUser();
$user= new user();
$data->fill(Auth::user());
$data->id_user = Auth::get('id');
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
and this is function Login
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
$data = user::where('email',$email)->first();
if($data) //check email apakah ada atau tidak
{
if(Hash::check($password,$data->password))
{
Session::put('id',$data->id);
Session::put('full_name',$data->full_name);
Session::put('email',$data->email);
Session::put('login',TRUE);
return redirect('userdt');
}
else
{
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
}
}
this is the routes files
Route::get('/index','UserController#show')->name('surevey.index');
Route::get('/logout','UserController#Logout')->name('user.logout');
Route::post('/registerpost','UserController#RegisterPost')->name('user.register');
Route::post('/loginpost','UserController#LoginPost')->name('user.login');
//reward routes
Route::get('/reward','RewardController#index')->name('reward.list');
//profile
Route::put('/editprofile/edit/{id}','UserController#edit')->name('profile.edit');
Route::post('/editprofile/update','UserController#update')->name('profile.update');
Route::get('/userdt',['middleware'=>'auth','uses'=>'UserController#userdetail'])->name('userdt.show');
Route::post('/userdt/store','UserController#store')->name('userdt.store');
//Survei
Route::get('/createsurvey','SurveyController#show')->name('survey.create');
Route::get('/surveylist','SurveyController#index')->name('survey.list');
Auth::routes();
ModelUser
protected $fillable = [
'id_user',
'jenis_kelamin',
'no_tlp',
'jurusan',
'wilayah'
];
protected $table ='user_detail';
public function user()
{
return $this->belongsTo(user::class);
}
and I get error like this
Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must
be of the type array, null given, called in
E:\Laravel\surevey\app\Http\Controllers\UserController.php on line 110
You don't need to use $data->fill(Auth::user()); as you have only single user_id field need to set.
Also you can get the current logged in user's id using. \Auth::user()->id
So your code would be as follow:
$data = new ModelUser();
$data->id_user = \Auth::user()->id;
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
Note: Make sure you have included auth middleware with your route.
Like:
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
}]);
And you have followed the authuntication process carefully.
https://laravel.com/docs/5.2/authentication
Edited:
Your loging should be changed as:
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('userdt');
}
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
If your reverse one-to-one relationship in the User Model looks like this:
public function detail()
{
return $this->hasOne(ModelUser::class);
}
And you are sure a user is logged in, you could simply do this
$data = Auth::user()->detail()->save($request->all());
return redirect()->route('surveylist');
Laravel's ORM takes care of the rest.
should be Auth::id() or Auth::user()->id but seems like your Auth::user() is returning a null.make sure you sessions, routes are set up properly.
use Auth::attempt()to login user
I have this method in my DocumentsController and am trying to implement some simple permissions system, in that a user that is not an admin must have been assigned a branch and a department before adding, editing or deleting a Document.
Here is the code for the method
/**
* Check the credentials of the user that is not an admin
* to add, modify a document
*/
private function checkCredentials() {
$user = auth()->user();
// dd((!is_admin() && !$user->branch_id && !$user->department_id));
if (!is_admin() && !$user->branch_id && !$user->department_id) {
// dd(redirect()->route('documents'));
return redirect()->route('documents')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
}
And here is how am calling it in one of my controller methods that mapped to the route Route::get('/documents/add', ['as' => 'documents.add', 'uses' => 'DocumentsController#create',]);
public function create()
{
$this->checkCredentials();
...
return view('main/documents/create', $data);
}
Problem is the redirection is not working as it continues to display the form, even when the user has not yet been assigned a branch or department, that is when both the branch_id and department_id are both equal to null.
What could be the reason for this? Thank you.
You are not returning the redirect from the controller, try this:
/**
* Check the credentials of the user that is not an admin
* to add, modify a document
*/
private function checkCredentials() {
$user = auth()->user();
// dd((!is_admin() && !$user->branch_id && !$user->department_id));
if (!is_admin() && !$user->branch_id && !$user->department_id) {
// dd(redirect()->route('documents'));
return false;
}
}
public function create()
{
if(!$this->checkCredentials()) {
return redirect()->route('documents')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
...
return view('main/documents/create', $data);
}
I think you use authorization (gate/policy). https://laravel.com/docs/5.8/authorization
Your code need to be
<?php
private function checkCredentials() {
$user = auth()->user();
if (!is_admin() && !$user->branch_id && !$user->department_id) {
return redirect()->route('documents.add')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
}
public function create()
{
$this->checkCredentials();
//...
return view('main/documents/create', compact('data'));
}
I have the following database structure a users & roles table joined using a pivot table:
The users table contains all the info such as email and password, while the roles table defines the different roles :
roles table
1 -> admin
2 -> encoder
3 -> salesman
4 -> tech
Now the roles are defined many-to-many because, there are some encoders that are assigned also as an admin. Others may have an salesman+admin role, or even encoder+salesman. Basically it multiple roles can be assigned to someone.
Table Structure
users
id
email
roles
id
role
role_user
id
role_id
user_id
I know that if I do
$user = User::find(1)->email;
return $user;
the result would display the email of the user with ID 1.
I was trying to do $user = Auth::user()->roles; so that it will get the role of the currently authenticated user.
But doing so returns a JSON which displays all the roles the user is assigned to.
I was hoping to use this in a filter, to do something like this
$user=Auth::user()->roles;
if($user == 'admin')
{
//do something
}
else
{
//you are not an admin
}
if($user == 'encoder')
{
//do something
}
else
{
//you are not an encoder
}
Just a small fix for the code at the bottom:
public function hasRole($role = null) {
$hasRole = false;
$hasRole = !$this->roles->filter(function($item) use ($role) {
return $item->name == $role;
})->isEmpty();
return $hasRole;
}
#lozadaOmr: You have to add "use"!
Since it is a many-to-many relationship so you are getting a collection in the $user when you use following code:
$user = Auth::user()->roles;
So, you need to loop all the Role models and have to check if($someUser->role == 'admin') within the loop and in this case you may do it like this:
$roles = Auth::user()->roles;
$isAdmin = false;
$isAdmin = !$roles->filter(function($role) {
return $role->role == 'admin';
})->isEmpty();
if($isAdmin) {
// admin...
}
Also you may add a method in your User model like this:
// User model
public function isAdmin()
{
$isAdmin = false;
$isAdmin = !$this->roles->filter(function($item) {
return $item->role == 'admin';
})->isEmpty();
return $isAdmin;
}
So you can use:
if(Auth::user()->isAdmin()) {
// admin...
}
Update: Check any role:
public function hasRole($role = null)
{
$hasRole = false;
$hasRole = !$this->roles->filter(function($item) {
return $item->role == $role;
})->isEmpty();
return $hasRole;
}
Now you can use:
if(Auth::user()->hasRole('encoder')) {
//...
}