Iḿ trying to make an rest application using Phalcon, i save some of the info
of the logged in user in an session but i don't get this to work, my code:
$this->session->set( Sessions::USERINFO, array (
'login' => true,
'type' => UserTypes::ADMIN,
'username' => $this->user->getUsername(),
'adminid' => $this->user->getAdminID(),
'fullname' => $this->user->getFullName(),
'avatar' => $this->user->getAvatar() )
);
return $this->session->get( Sessions::USERINFO );
When he returns the session it works but when i try to get the session in an other request it returns empty
return array("session" => $this->session->isStarted(),
"session Data" => $this->session->get(Sessions::USERINFO));
isStarted returns true
get returns null
Sessions::USERINFO
is an class with const values
const USERINFO = "userInfo";
Session var creation
$di->setShared( 'session', function () {
$session = new Session();
$session->start();
return $session;
} );
I am using this to save my session:
$obj = $this->request->getJsonRawBody();
$user = Users::findFirstByUsername($obj->username);
if($user) {
if($this->security->checkHash($obj->password, $user->password)) {
unset($user->password);
$this->session->set('auth', $user->toArray());
$response = $user->toArray();
}
else {
$response = array('msg' => 'failed');
}
}
else {
$response = array('error' => 'User not found');
}
$this->setPayload($response);
return $this->render();
And this to recieve information from my session
if($this->session->get('auth')['username']) {
$response = $this->session->get('auth');
}
else {
$response = array('msg' => 'noInfo');
}
$this->setPayload($response);
return $this->render();
This is how I start my session:
$di->set('session', function () {
$session = new SessionAdapter();
$session->start();
return $session;
});
It works just fine, you might want to try this.
I found the problem. Had to enable this in my frondend application:
RestangularProvider.setDefaultHttpFields({
withCredentials: true
});
The frontend was not sending the cookie with every request.
Related
Using sessions we can achieve this, but need this without sessions or cookies.
<?php
class Employees extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew()
{
$response = array();
$this->auth(); // this value is always null returned by auth() method
}
}
?>
This is more of a OOP programming basics question. If you want to re-use a variable in another function of the same controller object, you have to set the variable globally for the Employees class and then set/get its value in your functions by using $this->yourVariableName. But the set value of the object instance can only be reused in that instance only. Which means that after the auth() function, another function should be called subsequently to "access" the $this->yourVariableName.
Another way is to pass the $jwtoken as a parameter to a function.
But the following code answers your question "How to pass calculated/final value of one function to other functions in a controller of Codeigniter application", if it doesn't, then your question should be corrected I guess.
Edit:
Ow ok, first the auth() function is being called, then you would like to pass the $jwtoken value to another function, am I right? Well once a function is finished executing, the variable "disappears" if not passed to another function. If you would like to process the $jwtoken value immediately within the auth() function, then the answer is to pass the $jwtoken value to another function from within the auth() function:
<?php
class Employees extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
// this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
$this->addNew($jwtoken);
// What is the addNew() supposed to do?
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew($jwtoken = "default_value_if_not_set") {
echo $jwtoken;
}
}
Since you are creating an API, I assume the API is a REST api and stateless, so there is no interference of sessions and cookies.
I assume your process works like this:
User does a login request from the app to the api and the api returns a token when the credentials check is valid
The token is stored in the app (in a local database for example) and used for other requests
So the only thing you need to do is (I assume you have a route to addNew):
public function addNew() {
$token = $this->input->get('token');
$loginData = $this->validateToken($token);
//... add new process
}
And from your app you need to pass the token with the request to the api.
How do you validate the token?
To obtain the data you have set in the token, you have to decode the token:
/**
* throws SignatureInvalidException
*/
function validateToken($token)
{
$jwt = new JWT();
return $jwt->decode($token, jwtSecretKey, 'HS256');
}
Code improvement
Avoid using sessions and cookies
Since your api is stateless, you have to avoid settings cookies or sessions. So in your controller you can remove the flash data helper:
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
# REMOVE THIS LINE
# $this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => "Wrong email or password", //CHANGE THIS LINE
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
# REMOVE THIS LINE
# $this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => "Scucessfully login!", //CHANGE THIS LINE
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
Return the output response instead of $jwtoken
In your response you have already set the the token, so you can simply return the response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($response));
Your query is vulnerable to sql injections
Use escape method around you variables or bind the params:
$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));
I would like to save sessions and cookies as discord does. What i mean? I mean when user sign in to discord account on browser and delete all cookies/session on browser by clicking padlock and cookies. When that will deleted everytime session file is created. And when i refresh site i was still logged on account. I want do something on this same way but when i use session, cookies, Header (to header i cant add expires date) And delete cookies by this same way it not adding that again because my script cant get any information about user. I thinking to do a JavaScript while to add every second sessionstorage or localstorage. And check that everytime when user open site but that is not good for optimalization. So anyone had idea how to do that?
Update
CreateInfo.php
<?php
namespace Client\Info;
use Client\Info\CheckInfo;
use Client\Info\SetInfo;
class CreateInfo
{
public function __construct()
{
$this->checkInfo = new CheckInfo();
$this->setInfo = new SetInfo();
$this->status = $this->checkInfo->getStatus();
}
public function control()
{
if($this->status['session'] && $this->status['cookie'] && $this->status['sameCookieSession']){
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, true, true);
}
}else if($this->status['session'] && $this->status['cookie'] && !$this->status['sameCookieSession']){
$this->setInfo->addCookie(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, true, false);
}
}else if($this->status['session'] && !$this->status['cookie']){
$this->setInfo->addCookie(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, false, false);
}
}else if(!$this->status['session'] && $this->status['cookie']){
$this->setInfo->addSession(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(false, true, false);
}
}else{
$this->setInfo->setAll();
}
}
public function run()
{
$this->control();
}
}
CheckInfo.php
<?php
namespace Client\Info;
use Client\Info\InfoDatabase;
use Client\Cookie\CookieFunction;
use Client\Session\SessionFunction;
use Client\Ip\IpFunction;
class CheckInfo
{
public function __construct()
{
$this->infoDatabase = new InfoDatabase();
$this->cookieFunction = new CookieFunction();
$this->sessionFunction = new SessionFunction();
$this->ipFunction = new IpFunction();
$this->session = $this->sessionFunction->getSession('client');
$this->cookie = $this->cookieFunction->getCookie('client');
}
public function checkExist($data)
{
if(!isset($data) || empty($data)){
return false;
}
if(!$this->infoDatabase->checkExistInDb($data)){
return false;
}
return true;
}
public function getStatus()
{
if($this->checkExist($this->cookie)){
if($this->checkExist($this->session)){
if($this->cookie == $this->session){
return[
'session' => true,
'cookie' => true,
'sameCookieSession' => true
];
}else{
return[
'session' => true,
'cookie' => true,
'sameCookieSession' => false
];
}
}else{
return[
'session' => false,
'cookie' => true,
'sameCookieSession' => false
];
}
}else{
if($this->checkExist($this->session)){
return[
'session' => true,
'cookie' => false,
'sameCookieSession' => false
];
}else{
return[
'session' => false,
'cookie' => false,
'sameCookieSession' => false
];
}
}
}
public function checkIpStatus()
{
$ip = $this->ipFunction->getIp();
$result = false;
if($this->getStatus()['session']){
$result = $this->infoDatabase->checkExistIpInDb($this->session, $ip);
}else if($this->getStatus()['cookie']){
$result = $this->infoDatabase->checkExistIpInDb($this->cookie, $ip);
}
return $result;
}
}
SetInfo.php
<?php
namespace Client\Info;
use Client\Info\InfoDatabase;
use Client\Cookie\CookieFunction;
use Client\Session\SessionFunction;
use Client\Ip\IpFunction;
use Client\Currency\CurrencyFunction;
use App\Element\Random\RandomString;
class SetInfo
{
public function __construct()
{
$this->infoDatabase = new InfoDatabase();
$this->cookieFunction = new CookieFunction();
$this->sessionFunction = new SessionFunction();
$this->ipFunction = new IpFunction();
$this->currencyFunction = new CurrencyFunction();
$this->randomString = new RandomString();
$this->cookie = $this->cookieFunction->getCookie('client');
$this->session = $this->sessionFunction->getSession('client');
}
public function addIp($session, $cookie, $sameCookieSession)
{
$ip = $this->ipFunction->getIp();
if($sameCookieSession){
$this->infoDatabase->addIp($this->cookie, $ip);
}else{
if($session){
$this->infoDatabase->addIp($this->session, $ip);
}else if($cookie){
$this->infoDatabase->addIp($this->cookie, $ip);
}
}
}
public function addCookie($session)
{
if($session){
$this->cookieFunction->setCookie('client', $this->session);
}
}
public function addSession($cookie)
{
if($cookie){
$this->sessionFunction->setSession('client', $this->cookie);
}
}
public function setAll()
{
$rand = $this->randomString->generate(128);
$ip = $this->ipFunction->getIp();
$currency = $this->currencyFunction->getCurrencyCode();
$this->infoDatabase->addCookie($rand);
$this->infoDatabase->addIp($rand, $ip);
$this->infoDatabase->addCurrency($rand, $currency);
$this->cookieFunction->setCookie('client', $rand);
$this->sessionFunction->setSession('client', $rand);
}
}
I created a new project in Laravel that consumes all data from an API. For private data like a user profile, I need an access token to get the data.
Once I have an access token, how do I set the token as Auth::id() in Laravel? Or perhaps I can store the user profile as Auth::user() so that I can use #auth in a frontend blade file?
class CustomAuthController extends Controller
{
public function index()
{
return view('login');
}
public function store(Request $request)
{
$request->validate([
'phone' => 'required|numeric'
]);
$data = [
'phone' => $request->phone
];
$codeSent = GeneralFunction::WebRequestPublicApi('first-login', $data, null, null, null, true);
if($codeSent->status == "success")
{
return redirect('verify');
} else {
$errors = new MessageBag();
$errors->add("phone", "Invalid phone number");
return view('login')->withErrors($errors);
}
}
public function showVerify()
{
return view('verify');
}
public function verify(Request $request)
{
try {
$request->validate([
'verify' => 'required|size:6'
]);
$data = [
'token_code' => $request->verify,
'source' => 'web'
];
$token = GeneralFunction::WebRequestPublicApi('verify-login', $data, null, null, null, true);
if($token->status === "success")
{
$userData = GeneralFunction::WebRequestPublicApi('membership', null, 'GET', null, null, true, $token->results->access_token);
if($userData->status !== "error")
{
$user = (array) $userData->results[0];
$request->session()->put('token', $token->results->access_token);
Auth::attempt($user, false, false);
return redirect('/');
}
} else {
$errors = new MessageBag();
$errors->add("verify", "Invalid Token");
return view('verify')->withErrors($errors);
}
} catch (Exception $e) {
$errors = new MessageBag();
$errors->add("verify", $e->getMessage());
return view('verify')->withErrors($errors);
}
}
}
I tried using Auth::attempt, Auth::login(), and the other method, but all of these required a user table. My project does not have a database.
You can do something like following.
In the controller
if($auth_ok)
{
session(['user' => ['key' => 'value', 'key2' => 'value2'] ]); // set session data
return view('frontend');
}
In the view
$user = session('user', false);
#if(!$user) // if not logged in
do something
#else // logged in successfully
Welcome my user
#endif
Hope this helps.
i guess the best thing you need to do is to use sqlite and once you got login from your api create a new user from it or find if there is existing already and Auth::login($newUser);
I'm using Socialite to get user information from facebook. All is going well but my redirect isn't working
Sub-routes
I read that it's not possible to do a redirect from a submethod, or
any method that's not in your routes.
But how else can i redirect the user after I logged them in?
My URL looks like this after the successfull facebook handshake
http://tmdb.app/auth/login/facebook?code=AQBTKNZIxbfdBruAJBqZ8xx9Qnz...
Code
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
return $authenticate->execute($request->has('code'), $this);
}
public function userHasLoggedIn($data)
{
$user = User::where('provider_id', $data->id)->first();
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
// NOT WORKING!
return redirect('test');
}
}
Your login function should be handling the redirect.
I'm guessing execute returns $data if the user is sucessfully logged in and false if not.
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
if($data = $authenticate->execute($request->has('code'), $this))
{
$user = User::where('provider_id', $data->id)->first();
// maybe delegate the user creation to another class/service?
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
return redirect('test');
}
return redirect('fail_view');
}
}
You can do it using PHP header function in Laravel sub method. I try it and works properly. Hope it can help you.
// You can using the following code
$url= url("about-laravel");
header("Location:" . $url);
exit;
// Or using the following code to redirect and keep set flash message
$result= $this->yourMethod(); // return redirect($this->route)->with('flash_message', 'I\'m Flash Message'); for TRUE or NULL for false
if( $result ){
return $result;
}
Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}