How to create $token for email fortify Laravel? - passwords

I am overrinding default Fortify password reset to work like welcome email, where user get a link to email for creating new password.
public function store(UserCreateRequest $request): RedirectResponse
{
$token = Str::random(60);
$user = User::create(array_merge($request->validated(),
['password' => bcrypt(Str::random(8))]));
$user->sendPasswordCreateNotification($token);
}
This way token is not acceptable? What I am doing wrong here?

This code did the correct $token for me.
$token = app(Illuminate\Auth\Passwords\PasswordBroker::class)->createToken($user);

Related

Login a user to wordpress from external application

Hi I am building a React native app based on my wordpress website so I need to make a registration and login logic to get the user id and user data, thankfully I made the registration logic by creating new user using the rest api, but I need help in making the login thing since I find nothing helpful while searching Google.
I want to post the username or email and the password to authenticate that the user do exist in my site
register_rest_route(
'custom-plugin', '/login/',
array(
'methods' => 'POST',
'callback' => 'login',
)
);
}
function login($request){
$creds = array();
$creds['user_login'] = $request["username"];
$creds['user_password'] = $request["password"];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
echo $user->get_error_message();
return $user;
}
add_action( 'after_setup_theme', 'custom_login' );
Then your API will be created as
http://www.url.com/wp-json/custom-plugin/login
Try it with Postman You will get 200 as a response and user info
body:
{
"username": ""fakmamail#gmail.com",//or the username
"password": "t433434533"
}

Laravel 8 Jetstream how to redirect user to custom route after resetting password

I am using Laravel 8 jetstream for authentication. My question is, how can I redirect the user after resetting the password to the custom route? I don't want to redirect the user to the login page. I didn't find the route in all Fortify classes; I am sure it should override.
protected $redirectTo
But I don't know in which file I have to do this change.
Here’s what I ended up doing to have a redirect back to the login route after a user submits a password reset action:
Copy the file SuccessfulPasswordResetLinkRequestResponse.php from \vendor\laravel\fortify\Http\Responses\ to a folder on your project at app\Http\Responses.
In your new file SuccessfulPasswordResetLinkRequestResponse.php, change the namespace to:
namespace App\Http\Responses;
Open app\Providers\FortifyServiceProvider.php
Inside the boot() function add:
public function boot()
{
...
$this->app->singleton(SuccessfulPasswordResetLinkRequestResponseContract::class, SuccessfulPasswordResetLinkRequestResponse::class);
}
In this same FortifyServiceProvider.php file, add the namespaces:
use App\Http\Responses\SuccessfulPasswordResetLinkRequestResponse;
use Laravel\Fortify\Contracts\SuccessfulPasswordResetLinkRequestResponse as SuccessfulPasswordResetLinkRequestResponseContract;
In your new SuccessfulPasswordResetLinkRequestResponse.php file, edit the toResponse() function:
public function toResponse($request)
{
return $request->wantsJson()
? new JsonResponse(['message' => trans($this->status)], 200)
: redirect()->route('login')->with('status', trans($this->status));
}
Here's a helpful link that shows all of the response classes that Fortify uses at the time of this writing:
Overriding other Jetstream and Fortify functionality
EDIT: It is not recommended to edit a file in vendor, use BillD's solution.
Check out vendor\laravel\fortify\src\Http\Responses\PasswordResetResponse.php
You should be able to modify the response in the method:
/**
* Create an HTTP response that represents the object.
*
* #param \Illuminate\Http\Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function toResponse($request)
{
return $request->wantsJson()
? new JsonResponse(['message' => trans($this->status)], 200)
: redirect()->route('login')->with('status', trans($this->status));
}
I had the same issue using jetstream and found the accepted solution is better especially if there are admin and user models each has reset password functionality,
You don't need to edit PasswordResetResponse.php in vendor but simply:
copy it to App\Http\Responses
then as you can find /vendor/laravel/fortify/routes/routes.php
Route::post('/reset-password', [NewPasswordController::class, 'store'])
->middleware(['guest:' . config('fortify.guard')])
->name('password.update');
It points to /laravel/fortify/src/Http/Controllers/NewPasswordController.php.
Store function has the default PasswordResetResponse.php.
public function store(Request $request): Responsable
{
$request->validate([
'token' => 'required',
Fortify::email() => 'required|email',
'password' => 'required',
]);
$status = $this->broker()->reset(
$request->only(Fortify::email(), 'password', 'password_confirmation', 'token'),
function ($user) use ($request) {
app(ResetsUserPasswords::class)->reset($user, $request->all());
app(CompletePasswordReset::class)($this->guard, $user);
}
);
return $status == Password::PASSWORD_RESET
? app(PasswordResetResponse::class, ['status' => $status])
: app(FailedPasswordResetResponse::class, ['status' => $status]);
}
So only need to change is the namespace in NewPasswordController.php file to point to your PasswordResetResponse.php you've made.
use Laravel\Fortify\Contracts\PasswordResetResponse;
To--
use App\Http\Responses\PasswordResetResponse;

mautic - I want to add contact in mautic via api

I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.
use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.
In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.
these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)

allow both username and email in login laravel 5

I use laravel's 5 built in authentication for login. im spending hours finding where is the database query located at that has been use when login, I want to both allow email and username is the email box. Anyone knows where that database query located at? anyone knows how to allow both username and password on the authentication.
PS: to sharpen the details, I just want the user to allow them to login both username and email.
PS: again! Im running on laravel 5 not 4!
Define both a login and an password input in your form then the request should look like :
public function authorize() {
return true;
}
public function rules()
{
return [
'login' => 'required',
'password' => 'required'
];
}
Then your login function should look like :
public function login(LoginRequest $request)
{
$field = filter_var($request->input('login'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('login')]);
if ($this->auth->attempt($request->only($field, 'password')))
{
return redirect('/');
}
return redirect('/login')->withErrors([
'error' => 'You email/username or password combination is wrong.',
]);
}
This is an optimized version because instead of doing 2 attemps to verify the credentials for both : if is a username or if is a password, laravel will do the work with verifying if the given data points to an email login or username.

How to store google api (OAuth 2) permissions?

i'm using the examples provided in the "google-api-php-client"-Library (http://code.google.com/p/google-api-php-client/) to implement user login and authorization on my website with google services.
I didn't make any changes to the examples, except adding my Client-ID, etc..
The authorization itself works fine: Users can login and i can fetch the provided informations.
However, when leaving the page, the whole authorization procedure is called again; users are not remembered and need to grant permissions again, which is some kind of annoying and not typical for google-logins as i know them.
For example: On stackoverflow, i'm logged in with my google account.
Whenever i revisit this site, i'm logged in automaticly, or (if logged out) just have to log in again - i do not have to confirm the general rights again.
Using the examples on my site however, forces the user to allow access whenever the site is visited again.
Did i make any mistakes, when using the examples?
What do i have to do, to avoid the permission request over and over again?
Thanks in advance for any kind of help!
Use this code for first time to retrieve access_code and save it to database:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
const ACCESS_TOKEN=$_SESSION['token'];
//code here to save in database
?>
Once ACCESS_TOKEN is saved in database change code to:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
//ACCESS_TOKEN is already saved in database, is being saved on first time login.
$_SESSION['access_token'] = ACCESS_TOKEN;
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $service->about->get();
echo '<script>console.log('.json_encode($userinfo).');</script>';
$userinfoService = new Google_OAuth2Service($client);
$user = $userinfoService->userinfo->get();
echo '<script>console.log('.json_encode($user).');</script>';
}
?>
That works fine for me.
Based on the kaushal's answer:
<?php
require_once 'globals.php';
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_ID');
$client->setClientSecret('YOUR_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$client->setUseObjects(true);
//if no token in the session
if ($_SESSION['google_token'] == '') {
//get stored token from DB
$sToken = $oDb->getOne("SELECT `google_token` FROM `users` WHERE `u_id` = " . (int)$_SESSION['user_id']);
//if no stored token in DB
if ($sToken == '') {
//autentificate user
$client->authenticate();
//get new token
$token = $client->getAccessToken();
//set token in session
$_SESSION['google_token'] = $token;
// set token in DB
$oDb->Query("UPDATE `users` SET `google_token`='$token' WHERE `u_id` = " . (int)$_SESSION['user_id']);
} else {
$_SESSION['google_token'] = $sToken;
}
}
$client->setAccessToken($_SESSION['google_token']);
//do what you wanna do with clients drive here
?>
The Google Drive SDK documentation includes a complete PHP sample application that you can use as a reference to get started:
https://developers.google.com/drive/examples/php
Basically, once the user is logged in and you retrieve access token and refresh token, you store those credentials in a database and reuse them instead of asking the user to authenticate every time.