I have a sendOtp() method using which i have to send otp to the user for changing password in changePassword() method
i want to return the $otp from the sendOtp() to changePassword()
The sendOtp method
public function sendOtp($user_phone_number)
{
$otp = mt_rand(100000, 999999);
//sms login
$data = [
'data' => [
'otp' => $otp
]
];
return Response::json(
$data_with_status = array_merge($this->respondSuccess('otp sent'), $data)
);
}
The changePassword() method
public function changePasswordOtp($user_phone_number)
{
$user = User::where('phone_number', '=', $user_phone_number)->count();
if($user > 0) {
$this->sendOtp($user_phone_number);
//return response with sent otp
}
else {
return Response::json(
$this->respondFailure('User not found')
);
}
}
thank you
You can receive otp by following code:
public function changePasswordOtp($user_phone_number)
{
$user = User::where('phone_number', '=', $user_phone_number)->count();
if($user > 0) {
$result_otp = $this->sendOtp($user_phone_number);
$result_otp = json_decode($result_otp ,true);
$otp = $result_otp['data']['otp']; //return response with sent otp
}
else {
return Response::json(
$this->respondFailure('User not found')
);
}
}
Change your sendOtp like this :
public function sendOtp($user_phone_number)
{
$otp = mt_rand(100000, 999999);
//sms login
$data = [
'data' => [
'otp' => $otp
]
];
$responseMessage= $this->respondSuccess();
$responseArray = array_merge(responseMessage, data);
return Response::json($responseArray);
);
}
Related
Client error: POST https://discordapp.com/api/oauth2/token resulted in a 429 Too Many Requests response: {"code": 0, "message": "You are being blocked from accessing our API temporarily due to exceeding our rate limits freque (truncated...)
I am getting this error when i am trying to login into my web apllication using discord,I know i am exceeding rate limits i want to increase my rate limit,after sometime it has started working again but i do not want this error again cause i have live customer on my site
<?php
namespace App\Http\Controllers\Auth;
include base_path('vendor/autoload.php');
use RestCord\DiscordClient;
use App\Http\Controllers\Controller;
use App\Models\User;
use Laravel\Socialite\Facades\Socialite;
use App\Notifications\SendCredentials;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class DiscordLoginController extends Controller
{
public function login(){
return Socialite::with('discord')->scopes(['guilds','guilds.join'])->redirect(); //redirect to generated 0auth link
}
public function callback(){
function getTotalMembers($last_id, $membrs_total)
{
$discord = new DiscordClient(['token' => getenv('DISCORD_BOT_TOKEN')]);
if ($last_id == 0) {
$members = $discord->guild->listGuildMembers(['guild.id' => 815031226699874334, 'limit' => 1000]);
} else {
$members = $discord->guild->listGuildMembers(['guild.id' => 815031226699874334, 'limit' => 1000, 'after' => $last_id]);
}
$end = end($members);
$last_id = $end->user->id;
$membrs_total = array_merge($membrs_total, $members);
if (count($members) <= 999) {
return $membrs_total;
} else {
return getTotalMembers($last_id, $membrs_total);
}
}
$membrs_total = array();
$membrs_totals = getTotalMembers(0, $membrs_total);
$current_guilds_ids=array();
foreach($membrs_totals as $member){
array_push($current_guilds_ids,$member->user->id);
}
$user = Socialite::driver('discord')->stateless()->user();
if(in_array($user->id,$current_guilds_ids))
{
$accessTokenResponseBody = $user->accessTokenResponseBody;
if (!Auth::user()) { //handle user login
$users = User::where(['discord_id' => $user->id])->first();
if ($users) {
if(in_array($users->discord_id,$current_guilds_ids)){
User::where(['id' => $users->id])->update([ 'is_binded' => true,'is_verified'=>true]);
}
Auth::login($users);
return redirect()->route('home');
} else {
$users = User::where('email', $user->email)->first();
if (!$users) {
$users = new User();
$users->name = $user->name;
$users->email = $user->email;
$password = uniqid();
$users->password = Hash::make($password);
$users->discord_id = $user->id;
$users->discord_email = $user->email;
$users->is_binded = 1;
if ($user->user['verified'] == 1) {
$users->is_verified = 1;
}
$users->save();
$notifyUsers = User::where('email', $users->email)->get();
foreach ($notifyUsers as $notifyUser) {
$notifyUser->notify(new SendCredentials($notifyUser, $password));
}
Auth::login($users);
return redirect()->route('home');
}
}
} else {
$user_id = auth()->user()->id;
$users = User::where(['discord_id' => $user->id])->count();
if ($users == 0) {
User::where(['id' => $user_id])->update(['discord_id' => $user->id, 'discord_email' => $user->email, 'is_binded' => true]);
return redirect()->route('home');
} else {
User::where(['id' => $user_id])->update(['discord_id' => $user->id, 'discord_email' => $user->email, 'is_verified' => false]);
$customer_status = User::where(['id' => $user_id])->value('is_customer');
$client = new \GuzzleHttp\Client();
$request = $client->get( //perform check
'https://discordapp.com/api/users/#me/guilds',
[
'headers' => [
'Authorization' => 'Bearer ' . $accessTokenResponseBody['access_token'],
],
]
);
$response = json_decode($request->getBody()->getContents(), true); //decode response
foreach ($response as $key => $value) { //traverse result
if ($value['id'] == 815031226699874334) {
User::where(['id' => $user_id])->update(['is_verified' => true]);
alert()->success('Nice One', 'You are in SMT Proxies Discord.');
if ($customer_status == true) {
$client = new Client([
'headers' => [
'Authorization' => 'Bot ' . getenv('DISCORD_BOT_TOKEN'),
"Content-Type" => "application/json"
]
]);
$client->put('https://discordapp.com/api/guilds/815031226699874334/members/' . $user->id . '/roles/815046198791503914', []);
alert()->success('Nice One', 'You are in SMT Proxies Discord & got customer role');
}
break;
}
}
return redirect()->route('home');
}
}
}
else{
alert()->warning('Sorry You have to join our server first');
return redirect()->route('login');
}
}
}
This method i am using for storing currentTime in database using ajax call and its working
public function saveTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 404]);
}
$video = \App\Lession::where('id',$lession_id)->first();
$lesson_id = $request->lession_id;
$progress = $request->time;
//save them somewhere
$watch_history = $user->watch_history;
$watch_history_array = array();
if ($watch_history == '') {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
} else {
$founder = false;
$watch_history_array = json_decode($watch_history, true);
for ($i = 0; $i < count($watch_history_array); $i++) {
$watch_history_for_each_lesson = $watch_history_array[$i];
if ($watch_history_for_each_lesson['lession_id'] == $lesson_id) {
$watch_history_for_each_lesson['progress'] = $progress;
$watch_history_array[$i]['progress'] = $progress;
$founder = true;
}
}
if (!$founder) {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
}
}
$data['watch_history'] = json_encode($watch_history_array);
$check = User::where('id',$user->id)->update(['watch_history' => $watch_history_array]);
return response()->json(['message' => 'Time saved', 200]);//send http response as json back to the ajax call
}
But when I use this another method to get the time back for playback it's getting the array inside an array
public function getTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403]);
}
$user_video = User::where('id',$user->id)->first();
$array = $user_video->watch_history;
foreach ($array as $key => $value) {
echo $check;
}
}
My current Output in a database is as follows
[{"lession_id":"157","progress":"71.449464"},{"lession_id":"156","progress":"92.113123"}]
So help me to get the values out of that for each lession id
I am trying to implement the save() method after the self::restrictionMinimunBid($ request, $ karateka, $ bid) function, but I get the following error: "Method App\\Http\\Controllers\\BidController::save does not exist."
Here is my code:
$bid = Bid::where('id_participants', '=', $request->id_participant)
->where('id_karatekas', '=',$market->id_karatekas)
->where('bid', '=',$request->bid);
if(!$bid->count()){
$bid->id_market = $market->id;
$bid->id_group = $market->id_group;
$bid->id_karatekas = $market->id_karatekas;
$bid->id_participants = $request->id_participant;
self::restrictionMinimunBid($request, $karateka, $bid);
$bid->save();
$response = array('code' => 200, 'Bid' => $bid, 'msg' => 'Bid created');
}else{
$response = array('code' => 400, 'error_msg' => "Bid already registered.");
}
public function restrictionMinimunBid(Request & $request, $karateka, & $bid)
{
$allKaratekas = Karateka::all()
->map(function ($allKaratekas) use ($karateka, $request, $bid){
if($karateka->id == $allKaratekas->id ){
if($request->bid > $allKaratekas->value){
$bid->bid = $request->bid;
$msg ="The bid is more than the value of karateka";
var_dump($msg);
}
else{
$error ="The bid is less than the value ofmkarateka";
var_dump($error);
}
}
});
}
You can replace this one:
$bid = Bid::where('id_participants', '=', $request->id_participant)
->where('id_karatekas', '=',$market->id_karatekas)
->where('bid', '=',$request->bid);
To this:
$bid = Bid::where('id_participants', '=', $request->id_participant)
->where('id_karatekas', '=',$market->id_karatekas)
->where('bid', '=',$request->bid)->first();
i want to write a API for updating data in sql. I am using CI for it.I am new to this field.while i have written it is not working in localhost itself .Can anyone help me? I am attaching my controller and model here.it is showing an error like this page is not working
function editprofile($id,$data) {
$this->db->where(array('user_id' => $id));
$this->db->update('registrationdetails', $data);
if(!empty($id))
{
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$adminId = 1;
$AUTHENTIC_KEY = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$user_id=2;
$firstname ="aiswarya";
$lastname ="mathew";
$email ="aiswarya#gmail.com";
$password ="aiswarya";
$confirmpassword ="aiswarya";
$contactnumber ="999999999";
$gender ="female";
$address ="canada";
$department ="cse";
$designation ="swe";
$Admindetails = $this->common->CheckValidAdmin($adminId,$AUTHENTIC_KEY);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id
);
$data = array();
$data = array('firstname'=>$firstname,'lastname'=>$lastname,'email'=>$email,'password'=>$password,'confirmpassword'=>$confirmpassword,'contactnumber'=>$contactnumber,'gender'=>$gender,'address'=>$address,'department'=>$department,'designation'=>$designation);
$status = $this->user->editprofile($user_id,$data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}
function editprofile($data) {
if(!empty($data['user_id']))
{
$this->db->where(array('user_id' => $data['user_id']));
$this->db->update('registrationdetails', $data);
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$data['adminId'] = 1;
$data['AUTHENTIC_KEY'] = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$data['user_id']=2;
$data['firstname'] ="aiswarya";
$data['lastname'] ="mathew";
$data['email'] ="aiswarya#gmail.com";
$data['password'] ="aiswarya";
$data['confirmpassword'] ="aiswarya";
$data['contactnumber'] ="999999999";
$data['gender'] ="female";
$data['address'] ="canada";
$data['department'] ="cse";
$data['designation'] ="swe";
$Admindetails = $this->common->CheckValidAdmin($data['adminId'],$data['AUTHENTIC_KEY']);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id);
$status = $this->user->editprofile($data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}
I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}