Yii2: Adding assign role in signup models - yii2

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;
}

Related

Yii2 Login Only For One Page

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);

How to check if logged in user has a particular role in Yii2

Here is my code:
$user = \Yii::$app->user->identity->id;
if($user->has['dce']){
echo true;
}
else
{
echo false;
}
This is what I get:
Call to a member function has() on integer
You should use can() method:
return Yii::$app->user->can('dce');
You can find more info in documentation in Access Check section.
in rbac
create some Roles
$auth = Yii::$app->authManager;
$auth->removeAll();
$operator = $auth->createRole('operator');
$admin = $auth->createRole('admin');
$auth->add($operator);
$auth->add($admin);
$auth->addChild($admin, $operator);
add permission
$someaction = $auth->createPermission('someaction');
$someaction->description = 'ome action';
$auth->add($someaction);
and
$auth->addChild($admin, $someaction);
now
if(Yii::$app->user->can('someaction')){
return true;
} else{
return false;
}

Logging-in always wrong credentials - Yii2

I've customized the signup form according to my user table, after customizing it I tried signing up I filled up the password form using '123456' as a password. After finishing signing up it says the I input the wrong password?
Here's the method for the SignupForm model:
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->first_name = $this->first_name;
$user->middle_name = $this->middle_name;
$user->last_name = $this->last_name;
$user->contact = $this->contact;
$user->birth_date = $this->birth_date;
$user->type = $this->type;
$user->external_type = $this->external_type;
$user->status = $this->status;
$user->region_id = $this->region_id;
$user->barangay_id = $this->barangay_id;
$user->province_id = $this->province_id;
$user->city_municipal_id = $this->city_municipal_id;
return $user->save() ? $user : null;
}
User Model
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
I followed the right installation procedure of Yii2 advanced app, also I'm already done with the migration. Where did it go wrong?

Codeigniter session value access

I recently bought project management system, I was trying to add new forms but my forms are not working. I think my problem is the model, I am failing to get a session value (project_code) submitted to the database to make sure that the specific entry is visible to the specific project. The system I bought is ekushey available on codecanyon.
Model
function client_invoicing_add($project_code = '') {
//$data['project_code'] = $project_code;
//$data['project_code'] = $this->session->userdata('project_code');
$data['client_payment_milestone'] = $this->input->post('client_payment_milestone');
$data['client_payment_deliverables'] = $this->input->post('client_payment_deliverables');
$data['client_payment_date'] = $this->input->post('client_payment_date');
$data['client_payment_amount'] = $this->input->post('client_payment_amount');
$data['timestamp'] = strtotime($this->input->post('timestamp'));
$data['client_id'] = $this->session->userdata('login_user_id');
$data['project_code'] = $this->db->get_where('project' , array('project_id' => $project_id))->row()->project_code;
//$data['project_id'] = $this->db->get_where('project' , array('project_code' => $project_code))->row()->project_id;
$this->db->insert('client_invoicing' , $data);
}
Controller
// Client invoicing
function client_invoicing($param1 = '' , $param2 = '' , $param3 = '') {
if ($this->session->userdata('client_login') != 1) {
$this->session->set_userdata('last_page', current_url());
redirect(base_url(), 'refresh');
}
if ($param1 == 'add') {
$this->crud_model->client_invoicing_add($param2); // param2 = project code
}
if ($param1 == 'edit') {
$this->crud_model->client_invoicing_edit($param2); // param2 = client payment id
}
if ($param1 == 'delete') {
$this->crud_model->client_invoicing_delete($param2); // param2 = client payment id
}
}
you can use var_dump($this->session->all_userdata()); to print all session objects. and from them you can check if session is already set or not.
Session array is available through the $_SESSION global:
$name = $_SESSION['name'];
// or:
$name = $this->session->name
// or:
$name = $this->session->userdata('name');
If you want to retrieve all of the existing userdata
$_SESSION
// or:
$this->session->userdata();
Note : The userdata() method returns NULL if the item you are trying
to access does not exist.

How do i check and get my own methods value in OAuth2 .net WebApi2 application instead of Userid and password

I am trying to get and check values from database , don't want to use existing function like below .
public override async Task
GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
i want to check my own method and parameter instead of this method ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
Example: var user = await myclass.CheckResource(MAC,SerialNO, ProductKey);
Could you please suggest how to change it and return Token?