I tried to make auth API, I am success registed.
Than Signin can't success.
Please help me ,thanks.
public function login(Request $request)
{
try
{
if (!$request->has('Account')
|| !$request->has('Password'))
{
throw new Exception('Parameter missing');
}
$checkUser = DB::table('Users')->where('Account',$request->Account)->first();
if(empty($checkUser))
{
throw new Exception('No Data');
}
$data = ([
'Account' => $request->Account,
'Password' => $request->Password,
]);
if(!Auth::attempt($data))
throw new Exception('Verification error');
this db info.
Try following for register need to hash password before save in database:
User::create([
'Account' => $request->Account,
'CreateDateTime' => date('Y-m-d'),
'UpdatedDateTime' => date('Y-m-d'),
'Password' => Hash::make($request->Password),
]);
try this way it might helpful and evn ry validator also:
and if not sure about pass word then first debug
$table->string('password', 60)->nullable();
----------------------------------------------------
return Validator::make($data, [
'email' => 'required|email',
'password' => 'required',
]);
-----------------------------------------------
$user_data=User::where('username','=',$request->username)->first();
$userScope=$user_data->scope;
Input::merge([
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'scope' => 'admin'
]);
$credentials = $request->only(['grant_type', 'username', 'password','scope']);
$validationRules = $this->getLoginValidationRules();
$credentials["client_id"] = env('CLIENT_ID');
$credentials["client_secret"] = env('CLIENT_SECRET');
$this->validateOrFail($credentials, $validationRules);
try {
if (!$accessToken = Authorizer::issueAccessToken()) {
return $this->response->errorUnauthorized();
}
} catch (\League\OAuth2\Server\Exception\OAuthException $e) {
throw $e;
return $this->response->error('could_not_create_token', 500);
}
$accessToken["groups"][] = $userScope;
return response()->json(compact('accessToken'));
Related
It was works fine. But problem arise after migrating domain & hosting. When I tried to login/signup with google login, it connect with Client ID & Secret correctly. But after, it redirect to homepage without any data or profile showing. On other side, same Client ID & Secret works fine in localhost.
Route::post('googlelogin', 'Api\Auth\LoginController#googlelogin');
#Controller
public function googlelogin(Request $request){
$this->validate($request, [
'email' => 'required',
'name' => 'required',
'uid' => 'required',
'password' => ''
]);
$authUser = User::where('email', $request->email)->first();
if($authUser){
$authUser->google_id = $request->uid;
$authUser->fname = $request->name;
$authUser->save();
if(isset($authUser) && $authUser->status == '0'){
return response()->json('Blocked User', 401);
}
else{
if (Hash::check('password', $authUser->password)) {
return $response = $this->issueToken($request,'password');
} else {
$response = ["message" => "Password mismatch"];
return response($response, 422);
}
}
}
else{
$verified = \Carbon\Carbon::now()->toDateTimeString();
$user = User::create([
'fname' => request('name'),
'email' => request('email'),
'password' => Hash::make($request->password !='' ? $request->password : 'password'),
'google_id' => request('uid'),
'status'=>'1',
'email_verified_at' => $verified
]);
return $response = $this->issueToken($request, 'password');
}
}
I'd like to know how I can populate the email_verified_at column with a timestamp upon the user clicking on the Verify Email Address contained in the verification email that's being sent.
I thought it'd be a straightforward thing to do hence my attempt below in the EmailVerificationController.php file but it didn't work.
What am I doing wrong and how can I fix it? Any feedback is appreciated :)
Here's api.php
Route::group(['middleware' => ['auth:sanctum', 'verified']], function () {
Route::post('email/verification-notification', [EmailVerificationController::class, 'sendVerificationEmail']);
Route::get('email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
$request->fulfill();
return redirect('/');
})->name('verification.verify');
});
Here's EmailVerificationController.php:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
class EmailVerificationController extends Controller
{
public function sendVerificationEmail(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return [
'message' => 'Already Verified'
];
}
$request->user()->sendEmailVerificationNotification();
return ['status' => 'verification-link-sent'];
}
public function verify(EmailVerificationRequest $request)
{
if ($request->user()->hasVerifiedEmail()) {
return [
'message' => 'Email already verified'
];
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
$time = Carbon::now();
$timeStamp = $time->toDateTimeString();
User::create([
'email_verified_at' => $timeStamp
]);
}
return [
'message'=>'Email has been verified'
];
}
}
Here's AuthController.php
public function register(Request $request)
{
try {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'age' => 'required',
'password' => 'required|min:6',
]);
$data = $request->all();
$dbData = [
'name' => $data['name'],
'email' => $data['email'],
'age' => $data['age'],
'password' => Hash::make($data['password'])
];
$user = User::create($dbData);
event(new Registered($user));
return response()->json([
"status" => true,
"message" => "Registered Successfully!",
'token' => $user->createToken('tokens')->plainTextToken
]);
} catch(\Exception $e) {
Log::error($e->getMessage());
throw new \Exception($e->getMessage(), $e->getCode(), $e);
}
}
You need to implement Laravel’s Must Verify Email feature in the API registration
Follow this tutorial
I am building registration form with Passport in Laravel using repository pattern, and when I try to register with postman I get error
Undefined property: Illuminate\\Http\\Response::$id
It breaks when I try and return response like this
return response(['user' => $user, 'access_token' => $accessToken]);
but when I just return $user instead then it works fine, but I don't have access token then. How can I register succesfully with access token? Any help is appreciated. Here is my code.
AuthController.php
public function register(RegisterUserRequest $request)
{
try {
$user = $this->service->createNewUser($request);
return $this->returnResource($user);
} catch (\Exception $exception) {
return $this->failureJson($exception);
}
}
AuthService.php
public function createNewUser(BaseRequest $request)
{
DB::beginTransaction();
try {
$request['confirmation_hash'] = Str::random(50);
$request['password'] = Hash::make($request['password']);
$user = parent::create($request);
Mail::to($user['email'])->send(new ConfirmationMail($user)); // Send email to user to confirm his email!
$accessToken = $user->createToken('authToken')->accessToken;
DB::commit();
return response(['user' => $user, 'access_token' => $accessToken]); // HERE IT BREAKS!!!
} catch (\Exception $exception) {
DB::rollBack();
throw new \Exception($exception->getMessage());
}
}
UserResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'password' => $this->password,
'remember_token' => $this->remember_token,
'api_token' => $this->api_token,
'confirmation_hash' => $this->confirmation_hash,
'email_verified_at' => $this->email_verified_at,
'is_verified' => $this->is_verified,
'verification_expires_at' => $this->verification_expires_at
];
}
Inside your createNewUser try to just return user return $user and then inside your UserResource.php create the token ' api_token' => $this->createToken('authToken')->accessToken
I want to register a new user : the procedure is to call an api with a client id and a client secret and if everything is ok I save the user. If not I redirect with an error message.
But when I try to redirect to the register route inside my validator I got this error Call to a member function validate() on string.
protected function validator(array $data)
{
$messages = [
'client_secret.size' => 'Secret Id must be exactly 36 characters',
];
$client_id = $data['client_id'];
$client_secret = $data['client_secret'];
$access = $this->getAccessToken($client_id, $client_secret);
if($access == false){
return route('register');
}
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'role' => 'required|string',
'country' => 'required|string',
'client_id' => 'required|string',
'client_secret' => 'required|string|size:36'
], $messages);
}
I did that before seeing your answer. I think it's similar.
protected function validator(array $data)
{
$messages = [
'client_secret.size' => 'Secret Id must be exactly 36 characters',
'access_token.required' => 'We could not get an access token, make sure that the client id and the client secret are correct'
];
$input = [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'role' => 'required|string',
'country' => 'required|string',
'client_id' => 'required|string',
'client_secret' => 'required|string|size:36',
'access_token' => 'required|string|min:10'
];
$client_id = $data['client_id'];
$client_secret = $data['client_secret'];
$access = $this->getAccessToken($client_id, $client_secret);
if($access == false){
$data['access_token'] = 'false';
}else{
$data['access_token'] = $access ;
}
return Validator::make($data, $input, $messages);
}
This is a wrong implementation. The validator function returns route('register') on failing to get access token this a string returned. But at the same time if the access token is fetched, you return a validator instance. The code that calls this will try to run the validate method which would fail in the first scenario. And the way this function is coded, you can't redirect from within it. If you really need to then you could do something like this
Validator method
if($access == false) {
throw new \Exception('Failed to get access token');
}
Calling logic
try {
$validator = $this->validator($data);
} catch (\Exception $e) {
return redirect()->route('register');
}
if ($validator->fails()) {
// handle
}
OR
Validator method
if($access == false) {
return null;
}
Calling logic
$validator = $this->validator($data);
if ($validator === null) {
return redirect()->route('register');
}
if ($validator->fails()) {
// handle
}
I'm modifying the signup function that store user's data( email and password). I wish to include more data such as phone number, name and national ID. I tried but in mysql database it doesn't show anything. Here is what I have done :
public function signup(Request $request)
{
$credentials = $request->only([
'national_id' ,
'name' ,
'phone',
]);
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'sometimes|email|unique:users',
'password' => 'sometimes|min:6|confirmed',
'password_confirmation' => 'sometimes|min:3',
'national_id' => 'required','unique:national_id',
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
$user->national_id = $request->national_id;
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
when I dd($request->national_id it shows me the national_id data in postman, but in my database it's NULL.