I was created auth api, i using cookie for identify the authenticated user, but the cookie always return null. I already search the answer on google, but the problem dont solved
Check my code
AuthController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\Token;
class AuthController extends Controller
{
protected $email;
protected $token;
function loginAction(Request $data) {
$this->email = $data->email;
$validatorMsg = [
'email.required' => 'Email tidak boleh kosong',
'email.email' => 'Masukan email yang valid',
'email.exists' => 'Email tidak cocok dengan akun manapun',
'password.required' => 'Password tidak boleh kosong'
];
$validator = Validator::make($data->all(), [
'email' => 'required|email|exists:users,email',
'password' => 'required'
], $validatorMsg);
if ($validator->fails()) {
return response()->json([
'type' => 'error',
'message' => $validator->errors()
], 422);
}
$find = User::where('email', $this->email)->first();
if (Hash::check($data->password, $find->password)) {
$this->generateToken();
return response()->json([
'type' => 'success',
'message' => 'Authentication successfully',
'auth_token' => $this->token
], 200);
} else {
return response()->json([
'type' => 'error',
'message' => [
'password' => 'Password tidak sesuai dengan akun terkait'
]
], 401);
}
}
function registerAction(Request $data) {
$validatorMsg = [
'name.required' => 'Nama tidak boleh kosong',
'email.required' => 'Email tidak boleh kosong',
'email.email' => 'Masukan alamat email yang valid',
'email.unique' => 'Alamat email sudah terdaftar',
'password.required' => 'Password tidak boleh kosong',
'password.min' => 'Password harus lebih dari 6 karakter',
'password_confirmation.required' => 'Password belum di konfirmasi',
'password_confirmation.same' => 'Password tidak sama dengan password konfirmasi'
];
$validator = Validator::make($data->all(), [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6',
'password_confirmation' => 'required|same:password'
], $validatorMsg);
if ($validator->fails()) {
return response()->json([
'type' => 'error',
'message' => $validator->errors(),
], 422);
}
$this->email = $data->email;
$user = new User;
$user->name = $data->name;
$user->email = $data->email;
$user->password = Hash::make($data->password);
$user->save();
$this->generateToken();
return response()->json([
'type' => 'success',
'message' => 'Register succesfully',
'auth_token' => $this->token
], 200);
}
function generateToken() {
$this->token = str_random(50);
cookie('auth_token', $this->token, 1440);
$UID = User::where('email', $this->email)->first()->id;
$find = Token::where('user_id', $UID)->first();
if ($find != null) {
$token = Token::where('user_id', $UID)->first();
$token->auth_token = $this->token;
$token->save();
} else {
$token = new Token;
$token->user_id = $UID;
$token->auth_token = $this->token;
$token->save();
}
}
}
The controller show if user succesfully authentication this controller generate the cookie
RequireAuth.php (Middleware)
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Cookie;
use Closure;
use App\Token;
class RequireAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// cookie('auth_token', 'wkwkand', 1440);
$authToken = Cookie::get('auth_token');
$find = Token::where('auth_token', $authToken)->first();
dd($authToken);
if ($find != null) {
return redirect('/available');
}
return $next($request);
}
}
The middleware to verify user has auth_token or not, but i already set the cookie. And i check dd() the cookie got null value
You aren't passing the cookie to response.
Generating Cookie Instances
This cookie will not be sent back to the client unless it is attached to a response
instance
Check it here: https://laravel.com/docs/5.6/requests#cookies
Try this quick fix:
function registerAction(Request $data) {
$validatorMsg = [
'name.required' => 'Nama tidak boleh kosong',
'email.required' => 'Email tidak boleh kosong',
'email.email' => 'Masukan alamat email yang valid',
'email.unique' => 'Alamat email sudah terdaftar',
'password.required' => 'Password tidak boleh kosong',
'password.min' => 'Password harus lebih dari 6 karakter',
'password_confirmation.required' => 'Password belum di konfirmasi',
'password_confirmation.same' => 'Password tidak sama dengan password konfirmasi'
];
$validator = Validator::make($data->all(), [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6',
'password_confirmation' => 'required|same:password'
], $validatorMsg);
if ($validator->fails()) {
return response()->json([
'type' => 'error',
'message' => $validator->errors(),
], 422);
}
$this->email = $data->email;
$user = new User;
$user->name = $data->name;
$user->email = $data->email;
$user->password = Hash::make($data->password);
$user->save();
$cookie = $this->generateToken();
return response()->json([
'type' => 'success',
'message' => 'Register succesfully',
'auth_token' => $this->token
], 200)->cookie($cookie);
}
function generateToken() {
$this->token = str_random(50);
$cookie = cookie('auth_token', $this->token, 1440);
$UID = User::where('email', $this->email)->first()->id;
$find = Token::where('user_id', $UID)->first();
if (!$find) {
$token = Token::where('user_id', $UID)->first();
$token->auth_token = $this->token;
$token->save();
} else {
$token = new Token;
$token->user_id = $UID;
$token->auth_token = $this->token;
$token->save();
}
return $cookie;
}
Related
I have code in Laravel that allows users to log in using their OTP, and it will authenticate the login by using the OTP. For it to work on mobile, I need an access_token to show it as a response.
this is my code
public function phone_login_checker(Request $request){
$validator = Validator::make($request->all(), [
'phone' => 'required',
'otp_no' => 'required',
]);
if ($validator->fails()) {
return $this->sendError('', ['errors' => $validator->errors()]);
}
if ($user = DB::table('users')
-> where('otp_no', '=' , $request->input('otp_no'))
-> where('phone', '=' , $request->input('phone'))
->exists())
{
$userdetail = DB::table('users')-> where('phone', '=' , $request->input('phone'))->first();
Auth::loginUsingId($userdetail ->id, $remember = true);
$token = $userdetail->remember_token;
return response()->json([
'status'=>1,
'access_token' => "", // Here, I have to add the access token
'user' =>Auth::user(),
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
else{
return response()->json([
'action' => 'showError',
'type' => 'error',
'message' => 'otp is incorrect'
]);
}
}
how can i have access_token?
I have successfully coded the registration function and its working but I don't know how to send email confirmation link after registration successful. Because I am using JWT Auth for for login and sign up from flutter app with Laravel API.
My login code is:
public function loginapi(Request $request)
{
$input = $request->only('email', 'password');
$email = $request->email;
$jwt_token = null;
if (!$jwt_token = JWTAuth::attempt($input)) {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
]);
}
// get the user
$user = getuserbyemail($email);
$user_ver_status = $user->email_verified_at;
$verified;
if($user_ver_status != null || $user_ver_status != ''){
$verified = true;
}
else{
$verified = false;
}
return response()->json([
'success' => true,
'varified' => $verified,
'token' => $jwt_token,
'users' => $user
]);
}
My Registration Code is:
public function registerapi(Request $request)
{
$sponsor = $request->sponsor;
$username = $request->username;
$email = $request->email;
//$phone = $request->phone;
$password = $request->password;
$getemail = getuserbyemail($email);
$getusern = getuserbyusername($username);
//$getphone = getuserbyphone($phone);
$getSponsor = getuserbySponsor($sponsor);
if($getSponsor == null ||$getSponsor == ''){
return response()->json([
'success' => false,
'message' => 'Sponsor user dose not found...!',
], 401);
}
else if($getemail != null){
return response()->json([
'success' => false,
'message' => 'Email is already existed...!',
], 401);
}
else if($getusern != null){
return response()->json([
'success' => false,
'message' => 'Username is already existed...!',
], 401);
}
else{
$insertuser = insertUser($getSponsor->id, $username, $email, $password);
if($insertuser == "true"){
return response()->json([
'success' => true,
'message' => 'Your account has been registerd successfully...!',
]);
}
else if($insertuser == "false"){
return response()->json([
'success' => false,
'message' => 'There is an error while regestring your account...!',
]);
}
else{
return response()->json([
'success' => false,
'message' => 'There is an UnKnown error while regestring your account...!',
]);
}
}
}
This is my insertUser() Function:
function insertUser(string $sponsor, string $username, string $email, string $password){
$time_now = date("Y-m-d H:i:s");
$updated_at = $time_now;
$created_at = $time_now;
$sponsor_id = $sponsor;
$user_name = $username;
$user_email = $email;
//$user_phone = $phone;
$user_password = $password;
$createUser = User::create([
'sponsor_id' => $sponsor,
'user_name' => $user_name,
'email' => $user_email,
'phone' => null,
'earning' => 0,
'balance' => 0,
'city' => null,
'country' => null,
'image' => null,
'status' => 1,
'password' => Hash::make($user_password),
]);
if($createUser){
return "true";
}
else{
return "false";
}
}
It is registering successful but not sending the verification link on email. How can I achieve that?
Update the question:
I am using Laravel 8 version
I am using backpack laravel. Though I am also using Backpack's own authentication, yet I need to maintain a different customer table for App usage. For the customer table, I am using JWTAuth for token generation, but token generation gets failed each time.
public function register(Request $request)
{
$checkEmail = Customer::where('email', $request->email)->first();
if ($checkEmail) {
$response = [
'email_already_used' => true,
];
return response()->json($response);
}
$payload = [
'password' => \Hash::make($request->password),
'email' => $request->email,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'auth_token' => '',
];
try {
$user = new \App\Models\Customer($payload);
if ($user->save()) {
$token = self::getToken($request->email, $request->password); // generate user token
if (!is_string($token)) {
return response()->json(['success' => false, 'data' => 'Token generation failed'], 201);
}
$user = \App\Models\Customer::where('email', $request->email)->get()->first();
$user->auth_token = $token; // update user token
$user->save();
$response = [
'success' => true,
'data' => [
'id' => $user->id,
'auth_token' => $token,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
],
];
} else {
$response = ['success' => false, 'data' => 'Couldnt register user'];
}
} catch (\Throwable $e) {
echo ($e);
$response = ['success' => false, 'data' => 'Couldnt register user.'];
return response()->json($response, 201);
}
return response()->json($response, 201);
}
I believe there might be some issue with guards.
Do I need to specify something in app/config.php for this?
I have some problem when I want to make login, I got an issue for my Auth::attempt always false value, Is am I got something wrong in my code?
Controller :
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// Crypting password & c_password to md5
$md5_pwd = md5($pwd);
$md5_c_pwd = md5($c_pwd);
// Salt password & c_password
$password = crypt($md5_pwd, "asd");
$c_password = crypt($md5_c_pwd, "asd");
$data = new User();
if ($password == $c_password) {
$user = User::create([
'name' => $name,
'email' => $email,
'password' => $password,
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json(['error' => "Password doesn't match"], 401);
}
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
$md5 = md5($pwd);
$password = crypt($md5, "asd");
if (Auth::attempt(['email' => $email, 'password' => $password])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
I assume you messed up with Laravel Default Password Hashing System
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// $data = new User();
$user = User::create([
'name' => $name,
'email' => $email,
'password' => bcrypt($password . 'salt'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
if (Auth::attempt(['email' => $email, 'password' => $password . 'salt'])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
Try this code. I don't know what happened to your code about the password you tried to encrypt it in attempt.
public function login(LoginRequest $request) {
if(!Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'active' => true
])) {
return response()->json('Email or Password is incorrect', 500);
}
$this->user = Auth::user()->load('roles');
return $this->createUserAccessTokenResponse();
}
protected function createUserAccessTokenResponse() {
return response()->json([
'status' => 'success',
'data' => [
'token' => $this->user->createToken($this->user->name)->accessToken,
'user' => $this->user
],
], 200);
}
your problem is that laravel by default hashes the password. so when you do Auth::attempt it's going to hash the password you provided. And the result is what you get, it will always false.
Instead, you need to Other Authentication Methods.
Auth::login($user);
// Login and "remember" the given user...
Auth::login($user, true);
Above is the easiest way to fix your code.
It's recommended to hash your password rather than encrypting the password.
Hashing password in laravel is also
Hash::make($password);
And then you can use Auth::attempt to log in your user.
Laravel Auth uses the bcrypt hashing when saving password via model you may use either of the 2 method
$account->password = bcrypt("YOUR_PASSWORD"); or $account->password = Hash::make("YOUR_PASSWORD");
Then if you're dealing with the auth attempt function, just simply call the method like this
if($account = Auth::attemp(['email' => "YOUR_EMAIL#DOMAIN.COM", 'password' => "YOUR_PASSWORD"])){
//success login, do your extra job here
}else{
//invalid credentials here
}
Instead of using md5 or crypt use \Hash::make() it is much secure
I refactored your code and it does the same thing
You only need to rename your c_password to password_confirmation
Source
Below code does the same thing that your code do
public function register(Request $register)
{
$this->validate($register, [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$user = User::create([
'name' => $register->input('name'),
'email' => $register->input('email'),
'password' => $register->input('password'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
public function login(Request $request)
{
$request->merge(['password' => \Hash::make($request->input('password'))]);
if (Auth::attempt($request->only(['email', 'password']))) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
when you hashing password using crypt it has a key to unlock it that's why there is a decrypt but when you use Hash::make() it doesn't have a key to break or unlock it, it will check it's algorithm to see if given password is matching the algorithm that already exists in the database that's why crypt is not safe and Hash::make is much much more safe
I'm using laravel with JWT Auth to connect my laravel project to mobile, this is my api controller at laravel
public function login(Request $request) {
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
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
$user = Sentry::authenticate($credentials, false);
return response()->json([
'code' => '200',
'message' => 'success',
'last_updated' => $user->updated_at->format("Y-m-d\TH:i:s\Z"),
'data' => [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'token' => $token
]
]);
}
but how to set the credentials using email or username with this JWT?
If you are using "tymon/jwt-auth" package, then you can just pass the user object to the JWTAuth class and bam!, you can get the JWT token in return which you can use to make user go through the app.
$user = User::where('email', $email)
->orWhere('username', $username)
->first();
$token = null;
if (!$token = JWTAuth::fromUser($get_info)) {
return $this->respondInternalError( 'Can\'t generate the JWT token right now, try again later!', 'object', 400);
}
return response()->json([
'code' => '200',
'message' => 'success',
'last_updated' => $user->updated_at->format("Y-m-d\TH:i:s\Z"),
'data' => [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'token' => $token
]
]);
You can login using email or using the following format
public function login(Request $request)
{
//validate incoming request
$this->validate($request, [
'email_phone' => 'required|string',
'password' => 'required|string',
]);
try {
$login_type = filter_var( $request->email_phone, FILTER_VALIDATE_EMAIL ) ? 'email' : 'phone';
// return $login_type;
$credentials = [$login_type => $request->email_phone, 'password'=>$request->password];
if (! $token = Auth::attempt($credentials)) {
return response()->json($this->customResponse("failed", "Unauthorized"), 401);
}
return $this->respondWithToken($token);
} catch(JWTException $e) {
return response()->json($this->customResponse("failed", "An error occured, please contact support.", $user), 500);
}
}