Using Dancer2::Plugin::DBIC to pull values from database - json

I have a webapp where a user can log in and see a dashboard with some data. I'm using APIary for mock data and in my Postgres Database each of my users have an ID. These ID's are also used in the APIary JSON file with relevant information.
I'm using REST::Client and JSON to connect so for example the url for the user's dashboard is: "/user/dashboard/12345" (in Apiary)
and in the database there is a user with the ID "12345".
How can I make it so when the user logs in, their ID is used to pull the data that is relevant to them? (/user/dashboard/{id})? Any documentation or advice would be much appreciated!

The docs of Dancer2::Plugin::Auth::Extensible are showing one part of what you need to do already. In short, save the user ID in the session. I took part of code in the doc and added the session.
post '/login' => sub {
my ($success, $realm) = authenticate_user(
params->{username}, params->{password}
);
if ($success) {
# we are saving your user ID to the session here
session logged_in_user => params->{username};
session logged_in_user_realm => $realm;
} else {
# authentication failed
}
};
get '/dashboard' => sub {
my $client = REST::Client->new();
# ... and now we use the user ID from the session to get the
# from the webservice
$client->GET( $apiary . '/user/dashboard/' . session('logged_in_user') );
my $data = $client->responseContent();
# do stuff with $data
};

For those who want to know what I ended up doing:
Dancer2::Plugin::Auth::Extensible has
$user = logged_in_user();
When I printed this it showed me a hash of all the values that user had in the database including the additional ID I had. So I accessed the id with
my $user_id = $user->{user_id};
And appended $user_id to the end of the url!

Related

How To send PDF to a specific user from database via email?

This is my code for generate PDF and send it to admins. The problem it is sending all the bills stored in database to all. But I want to send specific bill to specific user. I have connected two tables using foreign key named property_id. I want to send bill to an admin whose property_id is similar to bill property_id. How to do that?
code::
$users = User::where('user_type', 'admin')->get();
foreach($users as $user) {
$data["email"] = $user->email;
$data["title"] = "From Admin";
$data["body"] = "Bill To Pay";
$pdf = PDF::loadView('emails.myTestMail', $data);
$mail = Mail::send('emails.myTestMail', $data, function($message) use($data, $pdf) {
$message->to($data["email"], $data["email"])
->subject($data["title"])
->attachData($pdf->output(), "Bill.PDF");
});
}
Everything is working fine. But it is sending all the information stored in bill table to all user. I want to send specific data to specific user.
Thank You.

cakephp 3 save data to database dont work after adding new column

Hey i want to save data to my database with cakephp 3.8. All works but i added a new field "created_by" and changed it in the models folder.
this is my RequestTable.php
public function validationDefault(Validator $validator){
.... (more, but not important)
$validator
->scalar('created_by')
->maxLength('created_by', 100)
->allowEmptyString('created_by');
return $validator;
}
My entity file "Request.php"
in the top
* #property string|null $created_by
and
protected $_accessible = [
... (more)
'created_by' => true,
];
My code where i want to save the data:
$request = $this->Requests->newEntity();
$session = $this->getRequest()->getSession();
if(!empty($session->read('Auth.User.username'))){
$this->request->data['Requests']['created_by'] = $session->read('Auth.User.username');
}
$request = $this->Requests->patchEntity($request, $this->request->getData('Requests'));
if ($result = $this->Requests->save($request)) {
...
}
At the empty check it goes in the clause. After the patchEntity the result is the correct data. The same in the save.
The column in the table looks like
created_by varchar(100) DEFAULT NULL
I dont know why it doesnt save the data. If someone have more questions about the code please ask :)
Without an error message. It would be hard to determine where is the flaw. One thing you might consider is checking the database if it is busy handling another process. If there are flood requests that makes your request locked.
I dont know why, but if I create a new database with the same schema it works. Thank you all for your help :)

putting if statement in api with laravel

I'm currently learning on how API works and my mentor gave me a task to create submit the form using API and store the data on database with laravel and the task also require mandatory if logic on some field.
I have succeeded with the first task (storing data to the database ) and I'm having difficulties writing the mandatory if.
I'm confused, on my task paper I'm told to create one controller, one model and two endpoints (request-schedule and request-leaving) where each endpoint should have some parameters.
and for the request-leaving parameter, there are 10 parameters, 6 of them have this requirement like (mandatory if request type Request Day Off)
There are 3 requests typewritten on there
1. Request Day off
2. Request Schedule
3. Change Schedule
I'm a super newbie in programming, does anyone know how to solve this?
public function CreateReqSchedule(Request $request)
{
$reqschedule = new B777();
$reqschedule->reqtype = $request->input('reqtype');
$reqschedule->startdate = $request->input('startdate');
$reqschedule->enddate = $request->input('enddate');
$reqschedule->reason = $request->input('reason');
$reqschedule->route = $request->input('route');
$reqschedule->actualschedule = $request->input('actualschedule');
$reqschedule->changetoschedule = $request->input('changetoschedule');
$reqschedule->swapcrewid = $request->input('swapcrewid');
$reqschedule->swapcrewschedule = $request->input('swapcrewschedule');
$reqschedule->note = $request->input('note');
$reqschedule->save();
return response()->json($reqschedule);
}
code above is my only work, I'm feeling anxious, because I've googled it myself but I'm still stuck.
So you are talking about validations. you can put laravel validation into it like below
Use required validation for mandotory data and return response in json
// Making validation for fields
$validator = \Validator::make($request->all(), [
'fields1' => 'required',
'fields2' => 'required',
'fields3' => 'required',
]);
if ($validator->fails())
{
// return response on validaton fails
return response()->json(['status'=>400,'errors'=>$validator->errors()->all()]);
}
// If validation passes store your data in database

Action after loginByCookie()

In my app, I'm using session to store some user's data (e.g. name, role). I'm using default User class on common/models from yii2 and I'm getting the data I need by user id.The problem is that the data I stored in session are lost if user resume their previous session without entering password (using remember me option). To solve this, I tried to modify and put the codes for saving user's data inside validateAuthKey() method in User since it's called when yii2 checking for authkey to resume session. As in:
public function validateAuthKey($authKey)
{
$user = Member::findOne(['account_id' => Yii::$app->user->id]);
// Save on session
Yii::$app->session->set('name', $user->first_name . ' ' . $user->last_name);
Yii::$app->session->set('position', $user->position);
// .. other data
return true;
}
As you can see, I use the id of logged user to find Member. But by doing this, I got "Trying to get property of non-object" exception from Yii::$app->user->id. I can only get the id after the login process is completed. After prying around, I found that loginByCookie() from User in vendor\yiisoft\yii2\Web is used to log in. Is there any way to save user's data without tampering codes on vendor? Maybe some kind of event after loginByCookie() is executed.
Create your own User model extends \yii\web\User
namespace frontend\components;
class User extends \yii\web\User
{
protected function afterLogin($identity, $cookieBased, $duration)
{
...Do something here...
parent::afterLogin($identity, $cookieBased, $duration);
}
}
Modify the config (main.php).
'components' => [
'user' => [
'class' => 'frontend\components\User',
'identityClass' => 'common\models\User',
...
]
]
Put the below code in common/config/bootstrap.php
The EVENT_AFTER_LOGIN will be called even if the user is logged in by cookie.
use yii\web\User;
use yii\base\Event;
Event::on(User::className(), User::EVENT_AFTER_LOGIN, function() {
$user = Member::findOne(['account_id' => Yii::$app->user->id]);
// Save on session
Yii::$app->session->set('name', $user->first_name . ' ' . $user->last_name);
Yii::$app->session->set('position', $user->position);
});

Retrieve session data Codeigniter

I'm working on a messaging system and want the user's userid to be posted to the database along with the message. Right now, the message is posting to the database, but with a user ID of 0.
How can I get the user ID from the session data to post to the database along with the message? Sidenote: I'm using Tank Auth for authentication. (From the mysql side, user_id in the message table is a foreign key referencing id in the users table).
Controller
function index() {
if ($this->input->post('submit')) {
$id = $this->input->post('user_id');
$message = $this->input->post('message');
$this->load->model('message_model');
$this->message_model->addPost($id, $message);
}
}
Model
function addMessage($id, $message) {
$data = array(
'user_id' => $id,
'message' => $message
);
$this->db->insert('message', $data);
}
For tank_auth, get the user_id using the following, and then assign that to your sessions
$user_id = $this->tank_auth->get_user_id();
Taken directly from CI's documentation:
Retrieving Session Data
Any piece of information from the session array is available using the
following function:
$this->session->userdata('item');
Where item is the array index
corresponding to the item you wish to fetch. For example, to fetch the
session ID you will do this:
$session_id = $this->session->userdata('session_id');
Note: The
function returns FALSE (boolean) if the item you are trying to access
does not exist.
So, if you have a piece of session data named user_id, you would access it like this:
$user_id = $this->session->userdata('user_id');