I'm trying to get work with social authentication using liknedin provider in Laravel 5.1 but it's giving me that exception.
I have implemented such authentication using "github" and "google" providers,but this one sounds weird regarding linkedin provider is built-in in Laravel 5.1
This is my redirect function
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
and my setting
'linkedin' => [
'client_id' =>env('LinkedIn_APP_ID'),
'client_secret' => env('LinkedIn_APP_SECRET'),
'redirect' => 'http://localhost:88/laravel/public/social/login/linkedin',
]
Have you registered your redirect URL in your LinkedIn application's configuration (https://www.linkedin.com/developer/apps)?
public function redirectToProvider()
{
return Socialite::driver('linkedin')->redirect();
}
public function handleProviderCallback(Request $request)
{
try
{
$provider_user = Socialite::driver('linkedin')->user();
}
catch ( Exception $e )
{
$request->session()->flash( 'alert-danger', 'Invalid request data detected! please try again.' );
return redirect( '/' );
}
dd($provider_user);
}
Related
I'm aware that password reset link can be customized by adding the below function in AuthServiceProvider.php
ResetPassword::createUrlUsing(function ($user, string $token) {
return 'https://example.com/reset-password?token='.$token;
});
This is my sendResetPassword function
public function sendResetPassword(Request $request) {
$request->validate(['email' => 'required|email']);
$status = Password::sendResetLink(
$request->only('email')
);
if ($status === Password::RESET_LINK_SENT) {
return response()->json(['message' => __($status)], 200);
} else {
return response()->json(['message' => __($status)], 500);
}
}
Now I'm wondering if there is a way to pass a domain from the sendResetPassword $request to the createUrlUsing function.
The main purpose of this is to avoid hardcoding the frontend URL in my API. I just want that the forgot password form in my frontend sends the email and also the domain.
Not sure if this is the best approach, but as soon I posted the question I found that this is a working solution:
ResetPassword::createUrlUsing(function ($user, string $token) {
return $this->app->request->headers->get('origin').'/reset-password?token='.$token;
});
I newbie in Laravel API. There is an update function which only allows users to update their own post. It worked. When users try to update other user's post, it alswo worked, but it shows the error like this image. Actually i want it show in response json.
I want to show message like this
{
"status": "error",
"message": "This action is unauthorized",
}
This is my code for PostController.
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
//this will check the authorization of user but how to make if else statement, if the post belong to the user it will show this json below but if the post belong to other, it will show error message(response json)
$post->content = $request->get('content', $post->content);
$post->save();
return fractal()
->item($post)
->transformWith(new PostTransformer)
->toArray();
}
This code for PostPolicy
public function update(User $user, Post $post)
{
return $user->ownsPost($post);
}
This is code for User model
public function ownsPost(Post $post)
{
return Auth::user()->id === $post->user->id;
}
This code for AuthServiceProvider
protected $policies = [
'App\Post' => 'App\Policies\PostPolicy',
];
Hope anyone can help me.
I'm using Laravel 5.4
In the app/Exceptions/Handler.php class you can change the render function like so
public function render($request, Exception $exception)
{
$preparedException = $this->prepareException($exception);
if ($preparedException instanceof HttpException) {
return response(
[
'message' => sprintf(
'%d %s',
$preparedException->getStatusCode(),
Response::$statusTexts[$preparedException->getStatusCode()]
),
'status' => $preparedException->getStatusCode()
],
$preparedException->getStatusCode(),
$preparedException->getHeaders()
);
}
return parent::render($request, $exception);
}
Or if you look further in the rendering, overriding the renderHttpException might be a little safer. This will remove the custom error pages in views/errors
protected function renderHttpException(HttpException $e)
{
return response(
[
'message' => sprintf(
'%d %s',
$e->getStatusCode(),
Response::$statusTexts[$e->getStatusCode()]
),
'status' => $e->getStatusCode()
],
$e->getStatusCode(),
$e->getHeaders()
);
}
I am making api in laravel. I am using the database that is already built and is live. That system uses md5 with salt values.
I want to do authentication for that system . how should do i have to do?
My source code :
public function authenticate(Request $request)
{
$email = $request->input('email');
$password = md5('testpassword' . 'saltvaluehere');
try {
//
// attempt to verify the credentials and create a token for the user
if (!$token = JWTAuth::attempt([
'email' => $email,
'pass' => $password
])
) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
In core php these authentication is done by:
$getpass = $mydb->CleanString($_POST['password']);
$getusername = $mydb->CleanString($_POST['username']);
$dbpass = $mydb->md5_decrypt($mydb->getValue("pass","tbl_admin","username = '".$getusername."'"), SECRETPASSWORD);
if($dbpass == $getpass){
return 'success full login';
}
above code doesnot give same value of hash, so i am not being able to authenticate in system.
Edited:
I have got the password that matched with database but token is not bieng generated.
here is my code:
public function authenticate(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
$password = md5($password);
try {
//
// attempt to verify the credentials and create a token for the user
if (!$token = JWTAuth::attempt([
'email' => $email,
'password' => $password
])
){
//return response()->json(compact('token'));
return response()->json(['error' => 'invalid_credentials','_data'=>[$password,$email]], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
can anybody tell me the reason why is token not being generated and why is it saying invalid credintials. as it shows the password and email of database of encrypted form.
This is a situation I've dealt with and I have foss code to give as a proof of concept.
Essentially, I added another password field for old passwords. I imported users with password_legacy set to a JSON object of old password data, in my case:
{ 'hasher' : 'algo', 'hash' : '#####', 'salt' : 'salt here' }
Then, I used a modified user service provider so that authentication checked for password_legacy if password was null. It then used the Illuminate Hasher contract as a base and constructed a new instance of a class (dynamically, using the hasher property, so for instance a app\Services\Hashing\AlgoHasher) and then used that for authentication instead of the default system.
If it did succeed, I bcrypt'd the password, set password and unsetpassword_legacy. This upgraded the password to the much higher standard of security that bcrypt offered.
Migration code for new field:
https://github.com/infinity-next/infinity-next/blob/ccb01c753bd5cedd75e03ffe562f389d690de585/database/migrations_0_3_0/2015_06_12_181054_password_legacy.php
Modified user provider:
https://github.com/infinity-next/infinity-next/blob/ccb01c753bd5cedd75e03ffe562f389d690de585/app/Providers/EloquentUserProvider.php
Hasher contract for Vichan (md5+salt):
https://github.com/infinity-next/infinity-next/blob/ccb01c753bd5cedd75e03ffe562f389d690de585/app/Services/Hashing/VichanHasher.php
Relevant user code:
https://github.com/infinity-next/infinity-next/blob/ccb01c753bd5cedd75e03ffe562f389d690de585/app/User.php#L124-L165
Hope that helps!
I am trying to create a login in Laravel 5.1 and I've not been able to login using this snippet. This is to allow a user to login using either username and password.
Controller class:
public function login(Request $request)
{
$field = filter_var($request->input('login'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('login')]);
if (Auth::attempt($request->only($field, 'password')))
{
return redirect()->route('home')->with('message', 'You have successfully logged in');
}
return redirect('login')
->with('message', 'Your username/password combination is not correct')
->withInput();
}
This is the reuest rules:
public function rules()
{
return [
'login'=>'required',
'password'=>'required'
];
}
What exactly is wrong? Kindly help me out. I appreciate.
I am currently building an Twitter client application for campus project using Codeigniter and Elliot Haughin Twitter library. It's just a standard application like tweetdeck. After login, user will be directed to the profile page containing timline. I am using Jquery to refresh the timeline every 20 second. At the beginning, everything run smoothly until i found the following error at the random time :
![the error][1]
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$request
Filename: libraries/tweet.php
Line Number: 205
I already search the web about this error but can't find satisfied explanation. So I tried to find it myself and found that the error comes out because credentials validation error. I tried to var_dump the line $user = $this->tweet->call('get', 'account/verify_credentials'); and resulting an empty array. My question is how come this error showed up when user already login and even after updated some tweets? is there any logical error in my script or is it something wrong with the library? Could anyone explain whats happening to me? please help me...
Here's my codes:
The Constructor Login.php
<?php
class Login extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('tweet');
$this->load->model('login_model');
}
function index()
{
$this->tweet->enable_debug(TRUE); //activate debug
if(! $this->tweet->logged_in())
{
$this->tweet->set_callback(site_url('login/auth'));
$this->tweet->login();
}
else
{
redirect('profile');
}
}
//authentication function
function auth()
{
$tokens = $this->tweet->get_tokens();
$user = $this->tweet->call('get', 'account/verify_credentials');
$data = array(
'user_id' => $user->id_str,
'username' => $user->screen_name,
'oauth_token' => $tokens['oauth_token'],
'oauth_token_secret' => $tokens['oauth_token_secret'],
'level' => 2,
'join_date' => date("Y-m-d H:i:s")
);
//jika user sudah autentikasi, bikinkan session
if($this->login_model->auth($data) == TRUE)
{
$session_data = array(
'user_id' => $data['user_id'],
'username' => $data['username'],
'is_logged_in' => TRUE
);
$this->session->set_userdata($session_data);
redirect('profile');
}
}
}
profile.php (Constructor)
<?php
class Profile extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('tweet');
$this->load->model('user_model');
}
function index()
{
if($this->session->userdata('is_logged_in') == TRUE)
{
//jika user telah login tampilkan halaman profile
//load data dari table user
$data['biography'] = $this->user_model->get_user_by_id($this->session->userdata('user_id'));
//load data user dari twitter
$data['user'] = $this->tweet->call('get', 'users/show', array('id' => $this->session->userdata('user_id')));
$data['main_content'] = 'private_profile_view';
$this->load->view('includes/template', $data);
}
else
{
//jika belum redirect ke halaman welcome
redirect('welcome');
}
}
function get_home_timeline()
{
$timeline = $this->tweet->call('get', 'statuses/home_timeline');
echo json_encode($timeline);
}
function get_user_timeline()
{
$timeline = $this->tweet->call('get', 'statuses/user_timeline', array('screen_name' => $this->session->userdata('username')));
echo json_encode($timeline);
}
function get_mentions_timeline()
{
$timeline = $this->tweet->call('get', 'statuses/mentions');
echo json_encode($timeline);
}
function logout()
{
$this->session->sess_destroy();
redirect('welcome');
}
}
/** end of profile **/
Default.js (The javascript for updating timeline)
$(document).ready(function(){
//bikin tampilan timeline jadi tab
$(function() {
$( "#timeline" ).tabs();
});
//home diupdate setiap 20 detik
update_timeline('profile/get_home_timeline', '#home_timeline ul');
var updateInterval = setInterval(function() {
update_timeline('profile/get_home_timeline', '#home_timeline ul');
},20*1000);
//user timeline diupdate pada saat new status di submit
update_timeline('profile/get_user_timeline', '#user_timeline ul');
//mention diupdate setiap 1 menit
update_timeline('profile/get_mentions_timeline', '#mentions_timeline ul');
var updateInterval = setInterval(function() {
update_timeline('profile/get_mentions_timeline', '#mentions_timeline ul');
},60*1000);
});
function update_timeline(method_url, target)
{
//get home timeline
$.ajax({
type: 'GET',
url: method_url,
dataType: 'json',
cache: false,
success: function(result) {
$(target).empty();
for(i=0;i<10;i++){
$(target).append('<li><article><img src="'+ result[i]['user']['profile_image_url'] +'">'+ result[i]['user']['screen_name'] + ''+ linkify(result[i]['text']) +'</li></article>');
}
}
});
}
function linkify(data)
{
var param = data.replace(/(^|\s)#(\w+)/g, '$1#$2');
var param2 = param.replace(/(^|\s)#(\w+)/g, '$1#$2');
return param2;
}
That's the codes. Please help me. After all, I really appreciate all comments and explanation from you guys. Thanks
NB: sorry if i had bad English grammar :-)
You are making a call to statuses/home_timeline which is an unauthenticated call. The rate limit for unauthenticated calls is 150 requests per hour.
Unauthenticated calls are permitted 150 requests per hour.
Unauthenticated calls are measured against the public facing IP of the
server or device making the request.
This would explain why you see the problem at the peak of your testing.
With the way you have it setup you would expire your rate limit after 50 minutes or less.
I suggest changing the interval to a higher number, 30 seconds would do. That way you'll be making 120 requests per hour and under the rate limit.