Angular - Display Dashboard and other component.html based on user_id - angularjs

Am unable to display component.html and dashboard based on user_id
I am using Angular to connect to Laravel endpoints. I have User model and other models. Every other tables have user_id in it. There are two dashboards: admin-dashboard and user-dashboard.
Laravel
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Email or Password doesn\'t exisit'], 401);
}
return $this->respondWithToken($token);
}
models for user, student and assignment:
protected $fillable = [
'name', 'email', 'password', 'username',
];
protected $fillable = [
'name', 'class', 'user_id',
];
protected $fillable = [
'title', 'valid_date', 'content', 'user_id',
];
Angular: Service
private baseUrl = 'http://localhost/cloudengine-sandbox/cloudsandboxbackend/public/api';
//private baseUrl = '/api';
constructor(private http:HttpClient) { }
register(data){
return this.http.post(`${this.baseUrl}/register`, data)
}
login(data){
return this.http.post(`${this.baseUrl}/login`, data)
}
login.component.ts
onSubmit() {
this.Jarwis.login(this.form).subscribe(
data => this.handleResponse(data),
error => this.handleError(error)
);
}
handleResponse(data){
this.Token.handle(data.access_token);
this.Auth.changeAuthStatus(true);
//this.user.loggedInUser = user;
this.router.navigateByUrl('/admindashboard');
}
When I login:
If user_id is 1, it should redirect to admindashboard else userdashboard
The admin should see everything in the application, while other users should see the components/forms that its table has the user_id of that particular user

Just add a if check inside the handleResponse method,
handleResponse(data){
if(this.user.user_id == 1){
this.router.navigateByUrl('/admindashboard');
}
else
{
this.router.navigateByUrl('/userdashboard');
}
}
better way to do this should be using a Using Route Guards.

Related

How to send notifications to Laravel Users with Onesignal notification channel?

I'm trying to use laravel-notification-channels/onesignal with Laravel 9, Inertia React project.
For first I setup the client in this way:
useEffect(() => {
OneSignal.init({
appId: "PRIVATE-KEY"
});
}, []);
Testing from Onesignal panel the client is listening.
For the back-end I have created a Notification:
<?php
namespace App\Notifications;
use NotificationChannels\OneSignal\OneSignalChannel;
use NotificationChannels\OneSignal\OneSignalMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\BroadcastMessage;
use App\Models\Order;
class OrderPlacedNotification extends Notification
{
use Queueable;
public $order;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(Order $order)
{
$this->order = $order;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database', 'broadcast', OneSignalChannel::class];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'order' => $this->order,
];
}
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'order' => $this->order
]);
}
public function toOneSignal($notifiable)
{
return OneSignalMessage::create()
->setSubject("Nuovo ordine!")
->setBody("Vedi l'ordine.")
->setUrl('http://onesignal.com');
}
}
and I send the notification via controller to all users.
All config setted but I can't listen to the user.
I found the solution. In my client I subscibe user to the specific interest and in backend I send notifictions at the users with that specific interest:
Frontend
useEffect(() => {
if(auth.user) {
window.Echo.private(`App.Models.User.${auth.user.id}`).notification(notification => {
console.log(notification);
setNotifications(() => [...notifications, notification]);
})
OneSignal.init(
{
appId: "KEY",
},
//Automatically subscribe to the new_app_version tag
OneSignal.sendTag("orders", "orders", tagsSent => {
// Callback called when tag has finished sending
console.log('TAG SENT', tagsSent);
})
);
}
}, [notifications]);
User Model:
public function routeNotificationForOneSignal()
{
return ['tags' => ['key' => 'orders', 'relation' => '=', 'value' => 'orders']];
}

save the record of bulk sms sent into db laravel

i have taken the id and mobile_num from users table.i have to insert that id name in this table as user_id,mobile_num,and status(0,1) into another table(wc_sms_status).sendSMSFunction is working fine.
public function SendBulkSms()
{
$usersNumber = User::select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
}
elseif($userNumber->mobile_num == exist && status == 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
}
else{
}
}
}
Do this :
public function SendBulkSms()
{
//assuming there is a relationship between your model users and wc_sms_status called wcSmsStatus
$usersNumber = User::with('wcSmsStatus')->select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
'user_id' => $userNumber->id,
'mobile_num' => $userNumber->mobile_num,
'status' => 1,
]);
} elseif ($userNumber->mobile_num && $userNumber['wcSmsStatus']->status === 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
} else {
}
}
}
public function SendBulkSms()
{
$users = User::select('id','mobile_num')
->whereIn('id', [5,6,7,8])
->whereNotNull('mobile_num')
->get();
$bulkData = [];
foreach ($users as $user)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
$bulkData[] = [
'user_id' => $user->id,
'mobile_num' => $user->mobile_num,
];
}
if (!empty($bulkData)) {
WcSmsStatus::insert($education); // change to your model name
unset($bulkData);
}
}
try to use in this way, it will insert bulk data, dont fergot to mention protected $fillable[] in model

How can I mock a validation provider in Cakephp

I have a validator that checks if a vat-number is correct. In order to do that it calls an external service. This external call slows the tests down and is unreliable, so I would like to mock it, but I don't understand how I could do it.
public function validationDefault(Validator $validator)
{
$validator->setProvider('vat', 'App\Model\Validation\VatValidation');
$validator->add('vat_no', 'isValidVatNo', [
'rule' => 'validVatNumber',
'provider' => 'vat',
]);
}
And this is the validation provider:
<?php
namespace App\Model\Validation;
use Cake\Core\Configure;
use Cake\Validation\Validation;
use VatNumberCheck\Utility\Model\VatNumberCheck;
class VatValidation extends Validation
{
public static function validVatNumber($check)
{
$vatNumberCheck = new VatNumberCheck();
try {
return $vatNumberCheck->check($check);
} catch (InternalErrorException $e) {
return false;
}
}
}
public function testValidationFail() {
$VatValidator = $this->getMockBuilder('Cake\Validation\Validator')
->setMethods(['validVatNumber'])
->getMock();
$VatValidator->expects($this->any())
->method('validVatNumber')
->will($this->returnValue(false));
$this->Users->getValidator()->setProvider('vat', $VatValidator);
$user = $this->Users->newEntity([
'vat_no' => 'asdf',
]);
$errors = $user->errors();
$this->assertArrayHasKey('vat_no', $errors);
}

I am facing A PHP Error was encountered

When I try to access my website member login area, I experiencing multiple errors those were not there earlier.
Please help me look into it.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: number
Filename: controllers/Site.php
Line Number: 42
Backtrace:
File:
/home/internetsunivers/2xcash.internetsuniversity.com/application/controllers/Site.php
Line: 42 Function: _error_handler
File: /home/internetsunivers/2xcash.internetsuniversity.com/index.php
Line: 315 Function: require_once A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home/internetsunivers/2xcash.internetsuniversity.com/system/core/Exceptions.php:271)
Filename: helpers/url_helper.php
Line Number: 564
Backtrace:
File:
/home/internetsunivers/2xcash.internetsuniversity.com/application/controllers/Site.php
Line: 50 Function: redirect
File: /home/internetsunivers/2xcash.internetsuniversity.com/index.php
Line: 315 Function: require_once
Following is the code in site.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Site extends MY_Controller {
public function index()
{
$this->header(':::SONNY SERVER:::');
$data['site_name'] = $this->site_name;
$this->load->view('home');
$this->footer();
}
public function about() {
$this->header('About | '.$this->site_name);
$data['site_name'] = $this->site_name;
$this->load->view('about');
$this->footer();
}
public function faq() {
$this->header('FAQ | '.$this->site_name);
$data['site_name'] = $this->site_name;
$this->load->view('faq');
$this->footer();
}
public function support() {
$this->header('Contact Support | '.$this->site_name);
$data['site_name'] = $this->site_name;
$this->load->view('support');
$this->footer();
}
public function login() {
$this->header('Login');
$this->form_validation->set_rules('number', 'Phone Number', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run()) {
if ($this->core_model->login()) {
$query = $this->db->get_where('users', array('number' => $number));
$result = $query->row_array();
$name = $result['name'];
$bank_details = $result['bank_details'];
$session_data = array('number' => $_POST['number'], 'loggedin' => TRUE, 'name' => $name);
$this->session->set_userdata($session_data);
redirect(site_url('dash'));
}
elseif ($this->db->get_where('users', array('number' => $this->input->post('number'), 'is_blocked' => 'true'))->num_rows() > 0) {
$this->session->set_flashdata('error', 'Account has been blocked, contact suppport');
} else {
$this->session->set_flashdata('error', 'Login failed');
}
$this->load->view('login');
} else {
$this->load->view('login');
}
}
public function register() {
$this->header('Register | '.$this->site_name);
$data['site_name'] = $this->site_name;
$this->form_validation->set_rules('name', 'Fullname', 'required');
$this->form_validation->set_rules('number', 'Phone Number', 'required');
$this->form_validation->set_rules('location', 'Location', 'required');
$this->form_validation->set_rules('bundle', 'Bundle', 'required');
$this->form_validation->set_rules('bank_details', 'Bank Details', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('c_password', 'Confirm Password', 'required|matches[password]');
if($this->form_validation->run()) {
$this->core_model->register();
//register session
$session_data = array('number' => $_POST['number'], 'loggedin' => TRUE, 'name' => $_POST['name'], 'bank_details' => $_POST['bank_details']);
$this->session->set_userdata($session_data);
$this->session->set_flashdata('msg2', 'Successfully registered');
redirect(site_url('spillover'));
$this->load->view('register');
} else {
$this->load->view('register');
}
$this->footer();
}
public function logout() {
$data = array('number', 'loggedin', 'name');
$this->session->unset_userdata($data);
redirect('login');
}
}

Override Model::save() or Implement Before/After Events? How Do I Fatten my Cake Models?

I find my edit actions in CakePHP controllers get messy pretty quickly, and I'd like to pull most of that crap into the Model. Let me give you a scenario.
I have an users/edit action in my Users controller. I want to let users reset a password (or not reset the password) in my form. If they provide a new password then I pass the three password fields into save() using the fields list parameter of save(). If they don't provide those fields I don't want to pass those fields in using the fields list.
The code to check these fields is currently in my controller, what would be a good way to move this into the model?
Here's what my controller's edit action looks like:
function edit($id = null) {
if ($this->Session->check('Auth.User') && $this->Session->read('Auth.User.id') == $id) {
if (!$id && empty($this->data)) {
$this->Session->setFlash('Invalid Account','default',array('class'=>'flash_error'));
$this->redirect(array('controller'=>'directories', 'action' => 'index'));
}
if (!empty($this->data)) {
// take out the following and an error occurs in parentNode()
$this->data['User']['group_id'] = 2;
if (empty($this->data['User']['old_password'])) { //TODO: pass in a field list for every publicly available save() call.
//dont update the password fields if they aren't passing in the old password
if ($this->User->save($this->data,true,array('first_name', 'last_name', 'email', 'username'))) {
$this->Session->setFlash('Your changes have been saved','default',array('class'=>'flash_ok'));
$this->redirect(array('controller'=>'directories','action'=>'index'));
} else {
$this->Session->setFlash('Your changes could not be saved. Please, try again.','default',array('class'=>'flash_error'));
}
} else {
//update the passwords
if ($this->User->save($this->data,true,array('first_name', 'last_name', 'email', 'username', 'password', 'password_confirm', 'old_password'))) {
$this->Session->setFlash('Your changes have been saved','default',array('class'=>'flash_ok'));
$this->redirect(array('controller'=>'directories','action'=>'index'));
} else {
$this->Session->setFlash('Your changes could not be saved. Please, try again.','default',array('class'=>'flash_error'));
}
}
}
if (empty($this->data)) {
$this->data = $this->User->read(array(
'first_name', 'last_name', 'email', 'username'
), $id);
}
$this->set('user_id',$id);
$this->set('current_subscription', $this->User->Subscription->currentSubscription($id));
} else {
//redirect to not authorized
$this->Session->setFlash('Invalid Account','default',array('class'=>'flash_error'));
$this->redirect(array('controller'=>'directories', 'action' => 'index'));
}
}
A more graceful style would be
function edit($id = null)
{
if($id && $this->Modelname->isValidLoginUser($id) && $this->data)
{
$login_tag = $this->Modelname->resetPass($id,$this->data);
switch($login_tag)
{
case 0: $this->Session->setFlash();$this->redirect();break;
case 1: $this->Session->setFlash();$this->redirect();break;
....
}
}
else
{
$this->Session->setFlash("missing arguments.");
}
}
And the function Modelname->resetPass() in the model looks like
function resetPass($id,$data)
{
$user = $this->findById($id);
$oldpasswd = $user[modelname]['password'];
$newpasswd = $data[modelname][passwd1];
$confirmpasswd = $data[modelname][passwd2];
if($newpasswd=="" || $confirmpasswd=="")
{
return 0;
}
if($newpasswd != confirmpasswd)
{
return 1;
}
....//perhaps other invalid situations
if($newpasswd == $oldpasswd)
{
$this->saveField("password",$newpasswd);
return N; //N is an int meaning success.
}
}

Resources