Getting Discord Authentication Error in Laravel - php

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

Related

Can't import excel data in Laravel 8. am new to it

**Am new to laravel8 trying to import data from excel sheet to the database, here is my code in the import class its not passing not giving any error. so the database has relationship am trying to import the data and make sure the relationships are considered so that l shouldn't have any problems **
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Models\District;
use App\Models\Organisation;
use App\Models\FocalPerson;
use App\Models\Ta;
use App\Models\Location;
use App\Models\Service;
use App\Models\Category;
use App\Models\Type;
class InformationImport implements ToCollection
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$instance_id = $row[1];
$organisation_name = $row[2];
$service_provider = $row[3];
$catchment_area = $row[4];
$organisation_type = $row[5];
$district_name = $row[6];
$organisation_web = $row[7];
$primary_name = $row[8];
$primary_title = $row[9];
$primary_number = $row[10];
$primary_email = $row[11];
$secondary_name = $row[12];
$secondary_number = $row[13];
$secondary_title = $row[14];
$secondary_email = $row[15];
$services_name = $row[16];
$location = explode(',',$row[17],2);
return $location;
$location_altitude = $row[18];
$location_accuracy = $row[19];
$comments_distance = $row[20];
$data_comments = $row[21];
$ta = Ta::where('name','like','%'.$row[4] .'%')->whereHas('district',
function($query) use($district_name){
$query->where('name','like','%'.$district_name .'%');
})->get();
if(!$ta){
$district = District::firstOrCreate([
'name' => $row[6]
]);
$ta = new Ta;
$ta->name = $row[4];
$district->tas()->save($ta);
}
$gvh = Gvh::firstOrCreate([
'name' => 'unknown',
'ta_id' => $ta->id
]);
$location = Location::firstOrCreate([
'latitude'=>$location,
'longitude'=>$location,
'gvh_id'=> $gvh->id
]);
$service = Service::firstOrCreate([
'name'=>$services_name
]);
$category = Category::firstOrCreate([
'name'=>'unknown'
]);
$type = Type::firstOrCreate([
'name'=>$organisation_type
]);
$organisation = Organisation::firstOrCreate([
'name'=> $organisation_name,
'location_id' => $location->id,
'organisation_type_id' => $type->id,
'organisation_category_id' => $category->id
]);
$focalperson =FocalPerson::firstOrCreate([
'title'=> $primary_title, $secondary_title,
'name' => $primary_name,$secondary_name,
'phonenumber'=>$primary_number,$secondary_number,
'email'=> $primary_email, $secondary_email
]);
}
}
}
**below is my controller class. in the controller that's the code l have because it wasn't bringing anything l had to write it in that way and see if it will be able to output the messages **
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\InformationImport;
use Maatwebsite\Excel\Facades\Excel;
class InformationController extends Controller
{
public function import(Request $request)
{
//Excel::import(new InformationImport, $request->file);
//return response()->json(['message' => 'Your data imported successfully !'], 200);
if ($request->ajax()) {
try {
Excel::import(new InformationImport, $request->file);
return response()->json(['message' => 'Your data imported successfully !'], 200);
} catch (ValidationException $ex) {
$failures = $ex->failures();
foreach ($failures as $failure) {
return response()->json(['message' => 'Row - ' . $failure->row() . ', ' . $failure->errors()[0]], 500);
}
}
}
return response()->json(['message' => 'Something went wrong !'], 500);
}
}
public function import(Request $request)
{
ini_set('max_execution_time', -1);
ini_set('memory_limit ', -1);
if ($request->ajax()) {
try {
$file_content = $request->file('excel');
$file_name = time() . '.xlsx';
Storage::disk('local')->putFileAs('public', $file_content, $file_name);
$url = "/app/public/" . $file_name;
$path = storage_path() . $url;
Excel::import(new InformationImport, $path);
return response()->json(['message' => 'Your data imported successfully !'], 200);
} catch (ValidationException $ex) {
$failures = $ex->failures();
foreach ($failures as $failure) {
return response()->json(['message' => 'Row - ' . $failure->row() . ', ' . $failure->errors()[0]], 500);
}
}
}
return response()->json(['message' => 'Something went wrong !'], 500);
}
This is sample and runnable code. Please refer
In Your Controller
public function import(Request $request){
$this->validate($request,[
'file'=> 'required|mimes:xlsx,csv'
]);
try{
Excel::import(new CannedResponseImport,request()->file('file'));
return back()
->withSuccess('Data imported successfully.');
}catch(\Exception $ex){
return back()
->withError('Someting went wrong please try again.');
}
}
In your Import
<?php
namespace App\Imports;
use App\Models\CannedResponses;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Validator;
class CannedResponseImport implements ToCollection,WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function collection(Collection $rows)
{
foreach ($rows as $row) {
if($row->filter()->isNotEmpty()){
if(!empty($row['business_type_id']) && !empty($row['brand_id']) && !empty($row['contact_reason_id'])
&& !empty($row['contact_sub_reason_id']) && !empty($row['personality_type_id']) && !empty($row['response_segment_id'])
&& !empty($row['response_tone_id']) && !empty($row['nature_conversation_id']) && !empty($row['canned_response'])
){
$id = CannedResponses::insertGetId([
'business_type_id' => $row['business_type_id'],
'brand_id' => $row['brand_id'],
'contact_reason_id' => $row['contact_reason_id'],
'contact_sub_reason_id' => $row['contact_sub_reason_id'],
'nature_conversation_id' => $row['nature_conversation_id'],
'personality_type_id' => $row['personality_type_id'],
'response_segment_id' => $row['response_segment_id'],
'response_tone_id' => $row['response_tone_id'],
'message' => $row['canned_response']
]);
}
}
}
}
}

How to access array values in laravel

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

Error in save() after an function in Laravel

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

Update query for API in codeigniter is not working

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

Laravel Accessing variable of other function

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

Categories