Laravel OTP with email only - laravel

I am trying to ingrate this flow of authentication in a Laravel 7 applciation:
User enters their email, submits the form.
User is sent to a form with a single input field;
System sends email to the user with a 10 (or whatever) digit code;
User inputs that code and is authenticated;
If on a later stage the user tries to enter the same email - same thing happens with a new code. No passwords or whatever.
Is there any way to achieve that out of the box (or with a package) or should I write it myself?

Yes, the efficient way to do is to inherit the laravel auth methods and change them accordingly. Make a resource controller by any name ex- UserController and write this code--
public $successStatus = 200;
public function login(Request $request){
Log::info($request);
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
return view('home');
}
else{
return Redirect::back ();
}
}
public function loginWithOtp(Request $request){
Log::info($request);
$user = User::where([['email','=',request('email')],['otp','=',request('otp')]])->first();
if( $user){
Auth::login($user, true);
User::where('email','=',$request->email)->update(['otp' => null]);
return view('home');
}
else{
return Redirect::back ();
}
}
public function sendOtp(Request $request){
$otp = rand(1000,9999);
Log::info("otp = ".$otp);
$user = User::where('email','=',$request->email)->update(['otp' => $otp]);
// send otp to email using email api
return response()->json([$user],200);
}
then add these routes to your routes file--
Route::post('login', 'UserController#login')->name('newlogin');
Route::post('loginWithOtp', 'UserController#loginWithOtp')->name('loginWithOtp');
Route::get('loginWithOtp', function () {
return view('auth/OtpLogin');
})->name('loginWithOtp');
Route::any('sendOtp', 'UserController#sendOtp');
and then add OtpLogin.blade.php view and you are good to go

Related

Laravel Nova how to overwrite the nova LoginController

My project requires a username rather than email. I had this working in Laravel 5.8 and Nova v2.1.0. After upgrading to L 6.x N 2.6.1 everything broke. So I started over with clean L 6.x and N 2.6.1 install.
Now I want to customize the login but I do not want to edit any Nova Package scripts as before.
I've added this code to nova/Http/Controllers/LoginController.php and all works as expected.
public function username()
{
return 'username';
}
When I add the code to App/Nova/Http/Controller/LoginController.php (a copy of the original) the login still requires an email address. Or is using the original file in nova.
this is what i do on my end
i override the App\Http\Controllers\Auth\LoginController.php from
class LoginController extends Controller
to
class LoginController extends \Laravel\Nova\Http\Controllers\LoginController
if you want to use username or email on the login page you have to add this.
this method will determine how the user input they credential
public function username()
{
$login = \request()->input("email");
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
\request()->merge([$field => $login]);
return $field;
}
because the user can login using email or username but the default login from nova only have 1 input box. have to add this to display if the user input wrong username or that username did not exist
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
'email' => [trans('auth.failed')],
]);
}
on my controller i have add other method to determine if the user is admin or able to access the backend or if the user is still active.
protected function authenticated(Request $request, $user)
{
if($user->isSuperAdmin()) {
return redirect(config('nova.path'));
}
if($user->can('backend')) {
return redirect(config('nova.path'));
}
return redirect('/');
}
by adding method to check user is active i need to add this method to check if the user can login
private function activeUser($username)
{
$user = User::where($this->username(), $username)->first();
if($user) {
return $user->active;
}
return false;
}
public function login(Request $request)
{
$active = $this->activeUser($request->only($this->username()));
if(! $active) {
return $this->sendFailedLoginResponse($request);
}
return parent::login($request);
}
hope this helps

Redirect::back() returning an empty url in laravel 4

I want to redirect back user to entered url after authenticating user
Scenario is: User enter a url, in backend I check for user to be authenticated and if user does not authenticated redirect user to login url and after successful login redirect user back to first url that user entered
Users Controller:
public function index()
{
if(!Auth::check())
{
return View::make('adminLogin');
}
return Redirect::to('admin');
}
public function login()
{
$creds = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if (Auth::attempt($creds))
return Redirect::back();
}
routes.php:
Route::resource('users', 'UsersController');
Route::post('login', 'UsersController#login');
filters.php:
Route::filter('logged', function($request)
{
if(!Auth::check())
return Redirect::to('users');
});
SettingController.php:
public function __construct()
{
$this->beforeFilter('logged', array('only' => array('index')));
}
public function index()
{
return View::make('setting');
}
Please help me.I'm a newbie in Laravel.
Use Redirect::intended('/'); instead of Redirect::back();.
PS: Also change
Route::filter('logged', function($request)
{
if(!Auth::check())
return Redirect::guest(URL::to('users')); //Your login form.
});
use the intended() method
The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.
example : return Redirect::intended('/');

How to logout a user from API using laravel Passport

I'm currently using 2 projects. 1 front end (with laravel backend to communicate with API) and another laravel project (the API).
Now I use Laravel Passport to authenticate users and to make sure every API call is an authorized call.
Now when I want to log out my user, I send a post request to my API (with Bearer token) and try to log him out of the API (and clear session, cookies,...)
Then on the client I also refresh my session so the token is no longer known. Now when I go back to the login page, it automatically logs in my user. (Or my user is just still logged in).
Can someone explain me how to properly log out a user with Laravel passport?
Make sure that in User model, you have this imported
use Laravel\Passport\HasApiTokens;
and you're using the trait HasApiTokens in the User model class using
use HasApiTokens
inside the user class.
Now you create the log out route and in the controller,
do this
$user = Auth::user()->token();
$user->revoke();
return 'logged out'; // modify as per your need
This will log the user out from the current device where he requested to log out. If you want to log out from all the devices where he's logged in. Then do this instead
$tokens = $user->tokens->pluck('id');
Token::whereIn('id', $tokens)
->update(['revoked'=> true]);
RefreshToken::whereIn('access_token_id', $tokens)->update(['revoked' => true]);
Make sure to import these two at the top
use Laravel\Passport\RefreshToken;
use Laravel\Passport\Token;
This will revoke all the access and refresh tokens issued to that user. This will log the user out from everywhere. This really comes into help when the user changes his password using reset password or forget password option and you have to log the user out from everywhere.
You need to delete the token from the database table oauth_access_tokens
you can do that by creating a new model like OauthAccessToken
Run the command php artisan make:model OauthAccessToken to create the model.
Then create a relation between the User model and the new created OauthAccessToken Model , in User.php add :
public function AauthAcessToken(){
return $this->hasMany('\App\OauthAccessToken');
}
in UserController.php , create a new function for logout:
public function logoutApi()
{
if (Auth::check()) {
Auth::user()->AauthAcessToken()->delete();
}
}
In api.php router , create new route :
Route::post('logout','UserController#logoutApi');
Now you can logout by calling posting to URL /api/logout
This is sample code i'm used for log out
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
]);
}
Create a route for logout:
$router->group(['middleware' => 'auth:api'], function () use ($router) {
Route::get('me/logout', 'UserController#logout');
});
Create a logout function in userController ( or as mentioned in your route)
public function logout() {
$accessToken = Auth::user()->token();
DB::table('oauth_refresh_tokens')
->where('access_token_id', $accessToken->id)
->update([
'revoked' => true
]);
$accessToken->revoke();
return response()->json(null, 204);
}
I am using Laravel 6.12.0, below function is working for me.
public function logout(Request $request){
$accessToken = Auth::user()->token();
$token= $request->user()->tokens->find($accessToken);
$token->revoke();
$response=array();
$response['status']=1;
$response['statuscode']=200;
$response['msg']="Successfully logout";
return response()->json($response)->header('Content-Type', 'application/json');
}
This is my first post.. and i find a clean solution (Laravel last Version)
/**
* Logout api
*
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
if (Auth::check()) {
$token = Auth::user()->token();
$token->revoke();
return $this->sendResponse(null, 'User is logout');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised'] , Response::HTTP_UNAUTHORIZED);
}
}
Below is the simplest way I found to do it.
1. USE database SESSION INSTEAD OF file SESSION
Official documention
php artisan session:table
php artisan migrate
Replace SESSION_DRIVER=file by SESSION_DRIVER=database in your .env file.
2. DELETE USER SESSION RIGHT AFTER LOGIN
After a user is redirected to your frontend and logs in to finally get a token, you probably call a route in api/routes.php to get the user information, that's where I'm closing the user backend session before sending back user information to the frontend:
Route::middleware('auth:api')->get('/user', function (Request $request) {
// Close user session here
Illuminate\Support\Facades\DB::table('sessions')
->whereUserId($request->user()->id)
->delete();
return $request->user();
});
3. REVOKE TOKENS AT LOGOUT
Then, to "log out" (actually, revoke tokens) the user from the frontend, you just need to call another route to revoke the token and refresh_token:
Route::middleware('auth:api')->post('/logout', function (Request $request) {
// Revoke access token
// => Set oauth_access_tokens.revoked to TRUE (t)
$request->user()->token()->revoke();
// Revoke all of the token's refresh tokens
// => Set oauth_refresh_tokens.revoked to TRUE (t)
$refreshTokenRepository = app('Laravel\Passport\RefreshTokenRepository');
$refreshTokenRepository->revokeRefreshTokensByAccessTokenId($request->user()->token()->id);
return;
});
You may prefer to put these two closures in the UserController.
Hope help someone:
if (Auth::check()) {
$request->user()->tokens->each(function ($token, $key) {
$token->delete();
});
}
Good Luck.
I use this in my project to logout from multiple device.
public function logout(Request $request, $devices = FALSE)
{
$this->logoutMultiple(\Auth::user(), $devices);
return response()->json([], 204);
}
private function logoutMultiple(\App\Models\User $user, $devices = FALSE)
{
$accessTokens = $user->tokens();
if ($devices == 'all') {
} else if ($devices == 'other') {
$accessTokens->where('id', '!=', $user->token()->id);
} else {
$accessTokens->where('id', '=', $user->token()->id);
}
$accessTokens = $accessTokens->get();
foreach ($accessTokens as $accessToken) {
$refreshToken = \DB::table('oauth_refresh_tokens')
->where('access_token_id', $accessToken->id)
->update(['revoked' => TRUE]);
$accessToken->revoke();
}
}
Try this code to help you to logout from passport authentication.
Route::post('/logout', function(){
if (Auth::check()) {
Auth::user()->AauthAcessToken()->delete();
}
return response()->json([
'status' => 1,
'message' => 'User Logout',
], 200);
});
check whether your model contains OauthAccessToken which needs to connect with the database oauth_access_tokens. The access token is stored in the database table oauth_access_tokens. and makes a relation from users to oauth_access_tokens.
public function AauthAcessToken(){
return $this->hasMany(OauthAccessToken::class);
}
You can use following code to remove to token for logged in user.
$request->user()->token()->revoke();
If you want to learn about this in-depth then watch this tutorial:
https://www.youtube.com/watch?v=UKSQdg1uPbQ
public function logout(Request $request)
{
$request->user()->token()->revoke();
if ($request->everywhere) {
foreach ($request->user()->tokens()->whereRevoked(0)->get() as $token) {
$token->revoke();
}
}
return response()->json(['message' => 'success']);
}

Customise Reset Password Email and pass User Data in Laravel 5.3

I am using Laravel 5.3 and customizing the Password Reset Email Template. I have done the following changes to create my own html email for the notification using a custom Mailable class. This is my progress so far:
ForgotPasswordController:
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return Response::json(['status' => trans($response)], 200);
case Password::INVALID_USER:
return Response::json(['email' => trans($response)], 400);
}
}
User Model:
public function sendPasswordResetNotification($token)
{
Mail::queue(new ResetPassword($token));
}
ResetPassword Mailable Class:
protected $token;
public function __construct($token)
{
$this->token = $token;
}
public function build()
{
$userEmail = 'something'; // How to add User Email??
$userName = 'Donald Trump'; // How to find out User's Name??
$subject = 'Password Reset';
return $this->view('emails.password')
->to($userEmail)
->subject($subject)
->with([
'token' => $this->token
'userEmail' => $userEmail,
'userName' => $userName
]);
}
If you noticed above, I am not sure how do I pass the user's name and find out the user's email address. Do I need to send this data from the User Model or do I query it from the Mailable class? Can someone show me how I can do that please?
Usually you ask for the user email in order to send a reset password email, that email should come as a request parameter to your route controller.
By default, L5.3 uses post('password/email) route to handle a reset password request. This route execute sendResetLinkEmail method which is defined in the 'SendsPasswordResetEmails' trait used by the App\Http\Controllers\Auth\ForgotPasswordController.
From here you can take one of 2 options:
1st: You could overwrite the route to call another function in the same controller (or any other controller, in this case could be your postEmail function) which search for the user model by the email you received, then you can pass the user model as function parameter to the method which execute the queue mail action (this may or may not require to overwrite the SendsPasswordResetEmails, depends on how you handle your reset password method).
This solution would looks something like this:
In routes/web.php
post('password/email', 'Auth\ForgotPasswordController#postEmail')
in app/Mail/passwordNotification.php (for instance)
protected $token;
protected $userModel;
public function __construct($token, User $userModel)
{
$this->token = $token;
$this->userModel = $userModel;
}
public function build()
{
$userEmail = $this->userModel->email;
$userName = $this->userModel->email
$subject = 'Password Reset';
return $this->view('emails.password')
->to($userEmail)
->subject($subject)
->with([
'token' => $this->token
'userEmail' => $userEmail,
'userName' => $userName
]);
}
in app/Http/Controllers/Auth/ForgotPasswordController
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$userModel = User::where('email', $request->only('email'))->first();
Mail::queue(new ResetPassword($token));
//Manage here your response
}
2nd: You could just overwirte the trait SendsPasswordResetEmails to search for the user model by the email and use your customized function in sendResetLinkEmail function. There you could use your function but notice that you still have to handle somehow an status to create a response as you already have it on ForgotPasswordController.
I hope it helps!

Use Plain Password in laravel 5 Authentication instead of bcrypt

i was using laravel bcrypt authentication in a back end application but client asked plain password authentication so that he can see the password of each user as administrator. My whole app logic is on laravel inbuilt authentication method an bcrypt hashing. how can i replace it to authenticate with plain password mach stored in database instead of storing hash ?
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
public function __construct()
{
$this->middleware('guest', ['except' => ['getLogout', 'getLogin']]);
}
public function postLogin()
{
$data = \Request::all();
$rules = [
'email' => 'required|email|max:255|exists:users',
'password' => 'required|exists:users'
];
$validator = \Validator::make($data, $rules);
if ($validator->fails()) {
//login data not exist in db
return redirect('/login')->withErrors($validator)->withInput();
} else {
$email = Request::input('email');
$pass = Request::input('password');
//in my table users, status must be 1 to login into app
$matchWhere = ['login' => $email, 'password' => $pass, 'status' => 1];
$count = \App\User::where($matchWhere)->count();
if ($count == 1) {
$user = \App\User::where($matchWhere)->first();
Auth::loginUsingId($user->id);
return redirect()->intended('/');
} else {
//not status active or password or email is wrong
$validator->errors()->add('Unauthorized', 'Not accepted in community yet');
return redirect('/login')->withErrors($validator)->withInput();
}
}
}
public function getLogin()
{
if (Auth::check()) {
return redirect()->intended('/');
} else {
return view('auth.login');
}
}
public function getLogout()
{
Auth::logout();
return redirect()->intended('/login');
}
}
If you are now using Laravel 5^, you can do that by searching for the class Illuminate/Auth/EloquentUserProvider and do some minor tweaks in there.
For e.g. find the public function retrieveByCredentials() and validateCredentials(). In the second function, you can see that the laravel is checking the hashed passwords to be fed into Auth::attempt() method. Just change it to plain checking and you are done.
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials)) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
return $query->first();
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
Change $this->hasher->check to normal check and you will be done. :)
In laravel 4 you could have rewritten the HASH module . This stackoverflow thread explains how to use SHA1 instead of bycrypt [ check the accepted answer and comments ] .
You can make use of the method explained here and save your password without hashing .
Well, that really compromises your client's website security.
Storing plain passwords in the DB is not recommended at all. If someone gained access to the database his/her site will be really vulnerable, anyone with a copy of the database would have easy access to all kind of accounts. I insist you should create a reset/change password functionality instead of storing plain passwords in the DB.
Anyway, you could just get the plain password with
$password = Input::get('password');
And I guess you could authenticate users with
if (Auth::attempt(array('password' => $password)))
{
return Redirect::route('home');
}
Wow, these are all so complicated, it's as simple as.
if ($user = User::where('email', request()->email)->where('password', request()->password)->first()) {
Auth::login($user);
return redirect()->to('/');
}
Though I do agree that in a production environment you should not do this. But I can see for some applications if the users are aware the passwords are stored in plain text it may be ok.

Resources