Yii2 Login Only For One Page - yii2

I have been attempting to implement an OpenID log-in with Yii2 today, and for the most part it has worked. Below is code from my controller, with the action 'Register' running through, and outputting the user->identity->username, but when I, say, redirect this action back to any page on the site, the logged in user is essentially forgotten. I can return to my Register action and have the user logged in.
Help would be appreciated. Thank you.
public function actionRegister()
{
require ('../views/site/steamauth/userInfo.php');
$localId = $_SESSION['steam_steamid'];
$foundUser = User::findOne(['steamid' => $localId]);
if(isset($foundUser))
{
Yii::$app->user->login($foundUser);
var_dump($foundUser);
echo Yii::$app->user->identity->username;
} elseif(!isset($foundUser)) {
$db = new User();
$db->steamid = $_SESSION['steam_steamid'];
$db->username = $_SESSION['steam_personaname'];
$db->visstate = $_SESSION['steam_communityvisibilitystate'];
$db->profile = $_SESSION['steam_profileurl'];
$db->avs = $_SESSION['steam_avatar'];
$db->avm = $_SESSION['steam_avatarmedium'];
$db->avf = $_SESSION['steam_avatarfull'];
$db->persstate = $_SESSION['steam_personastate'];
$db->save();
$foundUser = User::findOne(['steamid' => $localId]);
Yii::$app->user->login($foundUser);
return $this->goHome();
}
}
/**

Ah. After scouring Stackoverflow I found it.
The standard model function findIdentity
return isset(self::$usrs[$id]) ? new static(self::$usrs[$id]) : null;
must be change to reflect the new table of
return User::findOne($id);

Related

How to add new parameters to my URL - Laravel?

I need your help. So, I need to add more details on my URL. But what I did doesn't working. I need to add id of news on my link. Now, my link is like that : www.website.com/news/my-news-title, but it should be like that : www.website.com/news/88/my-news-title.
Here is my route:
Route::get('news/{id}/{slug}', 'ModelController#newsSingle');
Here is my view link:
Here is my controller:
public function newsSingle($slug, $id)
{
// return $slug;
$data = $this->data;
$data['news'] = News::with('category_name','news_image','models','creative')->where('slug','=',$slug)->orWhere('id','=',$id)->first();
if(count($data['news']) == 0)
{
abort(404);
}
updatNewsView($data['news']['id']);
// $displayitem = DisplayItem::where('slug','=',url('news'))->first();
// $data['page'] = $displayitem;
$data['title'] = $data['news']->title;
$data['breadcrumb'] = $data['news']->title;
// $data['menu'] = $tag->title;
$data['metadescription'] = $data['news']->metadescription;
$data['metatitle'] = $data['news']->metatitle;
// $data['blogs'] = $tag->blog;
return view('news.single_news',$data);
}
Now, the link is good, but when I'm trying to access it I get 404 error .
Your params are switched around in your controller. You have id/slug in your route but $slug, $id in your controller action.
Changing the following should work:
Controller:
public function newsSingle($id, $slug)
View:
Or use the named routes from mrhn's answer.
Your Url generation seems wrong, usually you would do named routes.
Route::get('news/{id}/{slug}', 'ModelController#newsSingle')->name('news');
Generate your url like this in the blade, by using the route helper that will return the url.

yii2 retrieve passwordHash for AccessTokenByUser

for use in Mobile App, I am trying to use Yii2 built in RestApi.
Now what I understand by the reading that we should disable session and set loginUrl property to false.
Now what I want is, I want a login screen for my app and want to authenticate against API.
how I can achieve the same.
Note:
I can authenticate with username and password for different controllers including users controller as well as bearer token.
also I read an example in" yii2 by example"
public function actionAccessTokenByUser($username, $passwordHash)
{
$accessToken = null;
$user = \app\models\User::findOne(['username' => $username, 'password_hash' => $passwordHash]);
//var_dump($passwordHash1);exit;
if($user!=null)
{
$user->access_token = Yii::$app->security->generateRandomString();
$user->save();
$accessToken = $user->access_token;
}
return [ 'access-token' => $accessToken ];
}
my question is how I get the `$passwordHash to supply here. I tried to look back and forth, but couldn't find any solution.
my main purpose is how I can implement a application login for mobile and thereon supply the accesstoken in the background wherever needed.
I believe I have refactored the code to achieve what I am looking. Open to suggestion or any flaw in my implementation.
here is what I have done.
public function actionAccessTokenByUser($username, $password)
{
$accessToken = null;
$username = \app\models\User::findByUsername($username);
if ($username!=null)
{
if($username->validatePassword($password)) $user = $username;
}
// $user = \app\models\User::findOne(['username' => $username, 'password_hash' => $passwordHash]);
if($user!=null)
{
$user->access_token = Yii::$app->security->generateRandomString();
$user->save();
$accessToken = $user->access_token;
}
return [ 'access-token' => $accessToken ];
}

Yii2: Adding assign role in signup models

I am using Yii2 basic template and I want to assign role when a user signs up.
Please check the following code:
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->fname = $this->fname;
$user->mname = $this->mname;
$user->lname = $this->lname;
$user->address = $this->address;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$auth = new DbManager;
$auth->init();
$getrole = $auth->getRole($this->role);
$auth->assign($getrole, Yii::$app->user->id);
return $user->save() ? $user : null;
}
Now, the problem here is that when a user signs up, user data will be saved and new assignment is inserted but user ID is incorrect.
You need to know user ID to attach role to it, and you can't know it before saving user to database. So you need to save user first and the assign role using ID from saved model:
if ($user->save()) {
$auth = new DbManager;
$auth->init();
$getrole = $auth->getRole($this->role);
$auth->assign($getrole, $user->id);
return $user;
}

not responding while login

I am new to CodeIgniter, and am trying to write code to log in after registering using a username and password in registration form using a PHPMyAdmin database. I am not getting anything when I try to log in, and it doesn't display an error or any message.
public function login() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password' , 'Password');
if($this->form_validation->run() == TRUE){
//check user in database
$this->db->select('username' , 'password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user = $query->row();
if($user->email){
$this->session->set_flashdata("Successful login");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
} else {
$this->session->set_flashdata("Error No such record found");
}
}
// load view and showing login form
$this->load->view('login');
}
First, you should read the documentation, looks like you skip that part, but it's very important!
Let's code a little bit and fix the bugs!
User data
Well, users will enter their data and we will check, if evertyhing is correct, we can redirect user to the protected page. You call for variables (see Query:) but you I'm not seeing on your code. You should put like that, before your query job
$username = $this->input->post("username");
$password = $this->input->post("password");
Now, you will be able to use the where to get the user data. =)
Query:
If read about OOP with PHP, you know that when you pass parameters to a method, each parameter have their own "action". In case of the select method, you should keep the data you want to select, on the same quote, because you the way you do, it's like you passing multiple parameters to the method.
$this->db->select('username, password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
First, to decide if the record exist or not, I prefer this way:
if($query->num_rows() > 0) {
$user_data = $query->row();
// We should verify if the user entered the password that correspond to the account.
// If not, we tell them that the password is incorrect.
if($password != $user_data->password) {
$this->session->set_flashdata("error", "Wrong password!");
return redirect(site_url());
}
// You can use the CI built in methods to work with sessions
$this->session->set_userdata(array(
'username' => $user_data->username,
));
$this->session->set_flashdata("success", "You are logged in!");
return redirect(site_url());
} else {
$this->session->set_flashdata("Error: No such record found");
redirect(site_url());
}
Flash data
Yeah, we use flashdata to show a message for the user. But, you should pass an item and the value of this item. Like that:
$this->session->set_flashdata('success', 'Successfully logged in!");
And, to retrieve the data on your views, you can do like...
<?php
$success = $this->session->flashdata("success");
$error = $this->session->flashdata("error");
if(!empty($success)) {
echo $success;
}
if(!empty($success)) {
echo $error;
}
?>
Recommendations
Sessions: https://codeigniter.com/userguide3/libraries/sessions.html
Database: https://www.codeigniter.com/userguide3/database/query_builder.html
Also, I recommed you, to take a minute on YouTube, to understand CodeIgniter.
If I forgot something, let me know! =)
Great Suggestion by webmasterdro's Answer.
I would like to extend it a little bit.
Looking at your code it looks like you have added the query to the controller.
And as a suggestion, if you are using an MVC framework then try to follow some basic MVC flow. because if you are not following that then it will be useless to use a framework.
User Controller to handle the post data and validations.
Use model to do the database query.
Use __construct for loading the common model or libraries.
Do not save plane password use md5 or other encryption technique.
Store User detail to the session which you can use further in after login.
Codeigniter has a great user guide. Try to follow that.
So, your code Should be your like this below.
Controller:
public function __construct() {
parent::__construct();
// Load model
$this->load->model('login_database');
}
public function your_controller_function_name() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form_view');
} else {
$username = $this->input->post("username");
$password = $this->input->post("password");
$result = $this->login_database->registration_insert($username, $password);
//You can do this also if($result != FALSE)
if (!empty($result)) {
// You can set other data to the session also form here
$session_data = array(
'username' => $result['user_name']
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
// You can set flash data here
$this->load->view('your_view');
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('your_login_form_view', $data);
}
}
}
Model:
// Read data using username and password
public function login($username, $password) {
$this->db->select('username');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user_data = $query->row_array();
if ($query->num_rows() == 1) {
return user_data;
} else {
return false;
}
}
I have not added detail related to flash data because the previous answer has explained it properly.

How to display data to view from db after insertion? [L5.2]

what I am trying to do here is after the insertion I want to display the data in the same page without refreshing the page
ROUTES
Route::post('viewBook/{bookId}', 'CommentsController#insertcomment');
//there's {bookId} cause of this http://localhost:8000/viewBook/1
CONTROLLER
public function insertcomment(Request $request)
{
$commenter = Auth::user()->id;
$comments = new Comments;
$comments->comment = $request->input('mycomment');
$comments->commenter = $commenter;
$comments->save(); //insert success
//getting the data
$data=DB::table('comments')
->select('comment')
->get();
return response()->json($data,true);
}
You don't need to get the data from DB again, just return inserted Comment object:
$commenter = Auth::user()->id;
$comment = new Comments;
$comment->comment = $request->input('mycomment');
$comment->commenter = $commenter;
$comment->save(); //insert success
return response()->json($comment, true);
In your situation.
In http://localhost:8000/viewBook/1. You should send a AJAX request to Route::post('viewBook/{bookId}', 'CommentsController#insertcomment');
Then get response from server for append to current comments HTML section. The response like #Alexey Mezenin answer