How do I set custom user claims upon registration in PHP Firebase? - php

I am trying to set a role on users upon registration on my PHP Firebase database but I only ever see instructions on how to do it after registration.
Is it actually impossible? If not then how do I do it? I've tried this
if(isset($_POST['register_btn']))
{
$fullname = $_POST['full_name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$password = $_POST['password'];
$role = $_POST['role_as'];
$userProperties = [
'email' => $email,
'emailVerified' => false,
'phoneNumber' => '+63'.$phone,
'password' => $password,
'displayName' => $fullname,
'role_as' =>$role,
];
if($role == "registrar")
{
$createdUser = $auth->createUser($userProperties);
if($createdUser)
{
$auth->setCustomUserClaims($key, ['registrar' => true]);
$_SESSION['status'] = "User created successfully.";
header('Location: login.php');
exit();
}
else
{
$_SESSION['status'] = "User creation failed.";
header('Location: register.php');
exit();
}
}
}
but it clearly didn't work. I'm seeing that I am missing the $key, which is supposed to be the ID of the user but as it's not registered yet, there is none. How would I do this?

As ADyson commented, the call to createUser returns a UserRecord that contains a $uid property.
Also see:
the definition of UserRecord in the library code

Related

How to change user email in PHP Firebase using CORE PHP not any framework

I'm working on a project where I need to update the user email in firebase. I'm using core PHP for that as it is the requirement of the project.
I'm following the official documentation and I'm able to delete the user successfully but when it comes to updating the email of the user I'm unable to do that. Any assistance you can provide would be greatly appreciated.
Following is the code snippet:
<?php
if(isset($_post['update_user'])){
$user_id = $_POST['user_id'];
$email = $_POST['email'];
$updateData = [
'email' => $email,
];
$updatequery_result = $auth->changeUserEmail($user_id,$updateData);
if($updatequery_result){
header('Location:manage_user.php');
}
else{
header('Location: index.php');
}
}
?>
Please note that the user email and user id are coming from an input field. So both email and id are being received on the current page.
Try this:
$updatequery_result = $auth->changeUserEmail($user_id,$updateData['email']);
This will work
<?php
if(isset($_post['update_user'])){
$user_id = $_POST['user_id'];
$email = $_POST['email'];
$updatequery_result = $auth->changeUserEmail($user_id,$email);
if($updatequery_result){
header('Location:manage_user.php');
}
else{
header('Location: index.php');
}
}
?>
**Don't take it in array **
No need of this code
$updateData = [
'email' => $email,
];

Disable WordPress Email/Username at The Registration Page

I created a website using WordPress. My website provides a registration page where users can enter several information in a form.
Is it possible to disable/delete the email and username at the registration page. Is there some php file or settings page where I can modify this behavior? I don't want such information to be required at all.
Any help is appreciated.
You must have atleast one of them fields i.e. either username or email, because you cannot login with just a password.
In the following example, I have used just username to register and ignored email field and registered a user via ajax call, this code is from functions.php file.
function register() {
global $wpdb;
$username = $_POST['username'];
$password = $_POST['password'];
$userdata = array('user_login' => $username, 'user_pass' => $password);
if (isset($username) && $username != '') {
$user_id = wp_insert_user($userdata);
wp_set_current_user($user_id, $username);
wp_set_auth_cookie($user_id, true, false);
$_SESSION['registered'] = 1;
update_user_meta($user_id, 'last_login', time());
if (is_wp_error($user_id)) {
$error_string = $user_id->get_error_message();
echo $error_string;
}
echo $user_id;
}
}

Problems with log in check

I write the following loginCheck code and the database schema I use is as follows:
userinfo:
username varchar
password varchar
code:
<?php
//set the MIME type to application/json
//header("Content-Type: application/json");
//get the username and password
$username = $_POST['username'];
$password = $_POST['password'];
//require database operation
require 'database.php';
$stmt = $mysqli->prepare ("SELECT username, password, COUNT(*) FROM userinfo WHERE username=?");
if(!$stmt){
echo json_encode(array(
"success" => false,
"message" => "an error occured, please try again"
));
exit;
}
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($returnedUsername, $hashedPassword, $count);
$stmt->fetch();
if ($count==1 && crypt($password, $hashedPassword) == $hashedPassword) {
//all information provided is correct, start a session
ini_set("session.cookie_httponly", 1);
session_start();
$previous_ua = #$_SESSION['useragent'];
$current_ua = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['username'] = $username;
if(isset($_SESSION['useragent']) && $previous_ua !== $current_ua){
die("Session hijack detected");
} else{
$_SESSION['useragent'] = $current_ua;
}
//create a token
$_SESSION['token'] = substr(md5(rand()), 0, 10);
echo json_encode(array(
"success" => true,
"token" => htmlentities($_SESSION['token']),
"username" => htmlentities($_SESSION['username'])
));
exit;
} else {
echo json_encode(array(
"success" => false,
"message" => "Incorrect Username or Password"
));
exit;
}
$stmt->close();
?>
The url is:
http://ec2-54-148-227-9.us-west-2.compute.amazonaws.com/~beibeixhb/Calendar/calendar.php
I am not sure why it prevent me from logging in, any suggestions?
You are using the hashed version of your password as a salt to the password entered and you expect that to be the same as the hashed password. I don't think this can ever happen.
crypt($password, $hashedPassword) == $hashedPassword
It's not clear from your code where you get the salt from, but if you didn't use salt to hash the password to start with, taking out that second argument of crypt should do the job for you.
Alternatively, use the right salt as a second argument to crypt.

PHP redirecting after incorrect login

So this script is from a tutorial I read so in honesty I don't understand every part of it as I'm new to PHP and this isn't all my code! (some is and some isn't)
So basically it's a login script, after login it redirects the user to an account page which is great. However if they enter the wrong login details it still redirects them to that page. This is obviously bad as it displays the users account page minus all the bits that are populated through a database connection to their details as this hasn't been established.
Here's my code that the HTML form submits to (I've copied the whole file but I believe the main code is at the bottom from "//store login status into the session" but I could be wrong of course:
<?php
include 'user.php';
include 'index.php';
$user = new User();
if(isset($_POST['signupSubmit'])){
//check whether user details are empty
if(!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['email']) && !empty($_POST['phone']) && !empty($_POST['password']) && !empty($_POST['confirm_password'])){
//password and confirm password comparison
if($_POST['password'] !== $_POST['confirm_password']){
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Confirm password must match with the password.';
}else{
//check whether user exists in the database
$prevCon['where'] = array('email'=>$_POST['email']);
$prevCon['return_type'] = 'count';
$prevUser = $user->getRows($prevCon);
if($prevUser > 0){
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Email already exists, please use another email.';
}else{
//insert user data in the database
$userData = array(
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'password' => md5($_POST['password']),
'phone' => $_POST['phone'],
'postcode' => $_POST['postcode'],
'travel' => $_POST['travel'],
'driver' => $_POST['driver'],
'main' => $_POST['main'],
'prop' => $_POST['prop'],
'hooker' => $_POST['hooker'],
'second_row' => $_POST['second_row'],
'flanker' => $_POST['flanker'],
'eight' => $_POST['eight'],
'scrum_half' => $_POST['scrum_half'],
'fly_half' => $_POST['fly_half'],
'centre' => $_POST['centre'],
'winger' => $_POST['winger'],
'full_back' => $_POST['full_back'],
'available' => $_POST['available'],
);
$insert = $user->insert($userData);
//set status based on data insert
if($insert){
$sessData['status']['type'] = 'success';
$sessData['status']['msg'] = 'You have registered successfully, log in with your credentials.';
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
}
}
}
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'All fields are mandatory, please fill all the fields.';
}
//store signup status into the session
$_SESSION['sessData'] = $sessData;
$redirectURL = ($sessData['status']['type'] == 'success')?'index.php':'registration.php';
//redirect to the home/registration page
header("Location:".$redirectURL);
}elseif(isset($_POST['loginSubmit'])){
//check whether login details are empty
if(!empty($_POST['email']) && !empty($_POST['password'])){
//get user data from user class
$conditions['where'] = array(
'email' => $_POST['email'],
'password' => md5($_POST['password']),
'status' => '1'
);
$conditions['return_type'] = 'single';
$userData = $user->getRows($conditions);
//set user data and status based on login credentials
if($userData){
$sessData['userLoggedIn'] = TRUE;
$sessData['userID'] = $userData['id'];
$sessData['status']['type'] = 'success';
$sessData['status']['msg'] = 'Welcome '.$userData['first_name'].'!';
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Wrong email or password, please try again.';
}
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Enter email and password.';
}
//store login status into the session
$_SESSION['sessData'] = $sessData;
//redirect to the home page
header("Location:http://www.example.com/successful_login.php");
}elseif(!empty($_REQUEST['logoutSubmit'])){
//remove session data
unset($_SESSION['sessData']);
session_destroy();
//store logout status into the ession
$sessData['status']['type'] = 'success';
$sessData['status']['msg'] = 'You have logout successfully from your account.';
$_SESSION['sessData'] = $sessData;
//redirect to the home page
header("Location:http://www.example.com");
}else{
//redirect to the home page
header("Location:index.php");
}
?>
I've tried changing:
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Wrong email or password, please try again.';
To:
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Wrong email or password, please try again.';
header("Location:www.loginpage.com");
But it makes no difference at all
You need to move header("Location:http://www.example.com/successful_login.php"); To just underneath: if($userData){ So that it looks like this:
if($userData){
$sessData['userLoggedIn'] = TRUE;
$sessData['userID'] = $userData['id'];
$sessData['status']['type'] = 'success';
$sessData['status']['msg'] = 'Welcome '.$userData['first_name'].'!';
header("Location:http://www.example.com/successful_login.php");
}
The reason why you are always getting redirected to the homepage is because the redirect code needs to be within some logic which basically says (pseudo code):
if(user is logged in){
redirectToHomePage;
} else {
showMessage('Incorrect password');
}

Header function not redirecting?

Please help
I have this php code(below) that creates and inserts a user into database after validating user inputs. I am storing the users input in an array. The problem is
It creates the user and inserts it to database but it does not redirect.
Here's the code
$validation = new Validate();
if($validation->passed()) {
//if success, insert(create) user
try {
$user = new User();
$salt = Crypt::salt(32);
$user->insert(array(
'username' => Accept::get('username'),
'password' => Crypt::make(Accept::get('password'), $salt),
'salt' => $salt,
'name' => Accept::get('name')
));
//After creation, redirect user
header('Location : index.php');
exit();
} catch(Exception $e) { //otherwise display errors
die("ERROR : CAN NOT REGISTER USER ".$e->getMessage());
}
This Code Creates user in database, but it does not redirect. I really don't understand why.
1) Make sure that you do not echo/output anything before the header() function not even blank space
2) write these at top of page to see errors
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
3) try ob_start(); or ob_flush();
ob_start();// at top of page
$validation = new Validate();
if($validation->passed()) {
//if success, insert(create) user
try {
$user = new User();
$salt = Crypt::salt(32);
$user->insert(array(
'username' => Accept::get('username'),
'password' => Crypt::make(Accept::get('password'), $salt),
'salt' => $salt,
'name' => Accept::get('name')
));
//After creation, redirect user
header('Location : index.php');
exit();
ob_flush();
} catch(Exception $e) { //otherwise display errors
die("ERROR : CAN NOT REGISTER USER ".$e->getMessage());
}

Categories