Register, Log In & Log Out
Every guest user can register to the BTT application. The view of menu bar is different for every type of user, for guest user it looks like this:
As we can see guest user have two options which are either to register or to log in if he already has an account.
Menu bar for logged in user looks like this:
The code that is responsible for visibility of certain elements of menu bar depending on authentication and authorization can be found in navigation section of almost every view:
if the users are logged in then thanks to @auth they can see the Logout option instead of Login one. If they aren't logged in they will see Login option as there is no authentication (based on session services built in that method) yet so the user isn't authorized to view it.
Same thing happens with My Account option, it is only visible to authorized users (logged in ones) with created session cookie.
The Register option is visible only to guest users thanks to @guest method as states that this option can be only shown for unauthenticated users.
Register
view for Register option:
In the view I created a simple form for registering new user. After unsuccessful registration previously filled in fields will save the entry thanks to value="{{ old('something')}}" method. The required makes sure that field won't be submitted empty and makes the browser show an error if an user tries to do it. If there are other validation issues (set up in controller) the error message regarding those will appear under the field it refers to thanks to @error method.
Controller for Registrer option:
use App\Models\User; tells us that this controller uses an User Model.
use App\Notifications\HelloEmail; it also uses the HelloEmail Notification.
return view('register.create'); shows us the view for registration form.
$attributes = request()->validate([array]); sets the attributes array that should be validated and then inserted to chosen table.
required states that the field can't be submitted empty.
email states that user's input should be in an email form (contain a ',' and '@').
unique states that the input shouldn't repeaat any record already existing in chosen table.
min sets the minimum characters that should be inserted for successful validation.
same states that an input should be identical as chosen input (same:password - in this case same as password field).
$attributes['password'] = bcrypt($attributes['password']); encrypts the password atribute so it is not visible in database in its base form and can't be read by a human being. It prevents account from being hacked.
$user = User::create($attributes); creates record with validated data in a user table (registers a user and creates their account).
$user->notify(new HelloEmail($user)); launches and sends a notifications of account creation to the user as a welcoming message.
auth()->login($user); logs user in as it detects authenticate session.
session() -> flash('success', 'message'); shows a message about successful account creation when the log in happens.
return redirect('/'); redirects user straight to home page.
HelloEmail Notification for sending Welcome emails to new users:
This file path is: /blog/app/Notifications/HelloEmail.php
Queueable allows us to defer the processing of a time consuming task until a later time.oute provides an array that contains the email address as the key.
mail r
toMail method is added as a notification supports being sent as an email.$notifiable entity returns an Illuminate\Notifications\Messages\MailMessage instance.MailMessage class contains methods that help with building transactional email messages.
Email Welcoming Message:
Register page:
Log In
View for Log In option:
In the view I created simple form for user to log in with. To do that user have to write their email and password. There is also a Reset Password option if the user forgot their password and want to change it in order to log in.
Controller for log in and log out option (session management):
store() function will start and store the session untill the user will log out (destroy it).
exists:users,email checks if email from user's input matches any existing record in users table in database.
(auth()->attempt($attributes)) checks user's authentication with attempt method which accepts an array of value pairs as its first argument. The values
in the array will be used to find the user in my database in users table. If the user is found by their email, the hashed password stored in the database will be compared with the password value passed to the method by the array. Password value here shouldn't be hashed, since the framework will automatically hash it before
comparing it to the hashed password stored in the database.
session()->regenerate(); sterts an authenticated session for the user if the two hashed
passwords match.
return redirect('/') ->with('success', 'message'); redirects logged users to home page and shows them a message about successful log in.
return back() take user back to the log in page if the authentication process is unsuccessful. withInput() method allows email input to be filled with previous value that user wrote which saves user's time as they don't have to rewrite it all over again after making a mistake.
withErrors(['password' => 'Wrong password or email.']); shows given error message if a mistake is made and the type of error isn't specified already by Laravel (so framework doesn't have ad default error message for it to dispaly).
destroy() function will destroy the session when user clicks the Log Out button.
auth()->logout(); will remove the authentication information from the user's session which will log them out of their accounts.
Log In page:
Forgot Password page:
Forgot Password view:
The view consists of a single input field form for user's email on which a reset password link will be sent. The user will have to click on a link to get to resetting password part.
Email with a Link for Password Reset View:
This file structures the email with a link for password reset. The link will use a token that keep the connection between email it was generated for and with an email that user will later pass in resetting form. It will prevent from user trying to change a password for an email that doesn't belong to them.
Email with a link looks like this:
Reset Password Page (accessable via link from email):
Reset Password View (after clicking the link in an email):
This view consists of a form asking about email, new password and new password confirmation (repeating it). Submitting the form will cause password reset and changing it for new one that user chose.
Controller for Forget/Reset Password option:
$token = Str::random(64); creates random token that will later be used in password reset, it will authorize resetting by connecting the reset link with an email that it belongs to in database.
DB::table('password_resets')->insert([]); orders inserting an array of values to the database table called password_resets. The array includes an email requested from user's input, generated token and creation time. created_at value will be filled by using Carbon::now() which returns the current time with a Carbon instance. Carbon makes it easy to work with timestamps.
Mail::send(); causes an email being send to given email address.
'token' => $token passes generated token to certain email address connection for reset link in email.forgetPassword (my email view).
$message->to($request->email); states who should be a receiver of that email which in this case will be an email address put by the user in an email input of the form.
return back()->with('message', 'We have e-mailed your password reset link!'); tells the user if the link has been successfully sent after they submit the form with an email.
confirmed is another way to set the password confirmation. It works along with _confirmation in value's name and if it finds one it will then see if both values, the one with confirmed in verification and with _confirmed in the name, are the same.
$request->validate([]); validates the user request, in this case it checks if given email exists in the database in users table and if two field inputs for password and its confirmations are the same.
$updatePassword = DB::table('password_resets')->where([]); states value's array from password_resets table that states, that an email from user's input should be the same as an email of the receiver of the link, and that token should be the same as the one matching that email and passed through the link.
first() method will return only one record.
return back()->withInput()->with('error', 'Invalid token!'); will show the message if an error of invalid input will occur.
$user = User::where('email', $request->email) matches the requested email with an email from users table and then by adding
->update(['password' => Hash::make($request->password)]); it updates the record with new, hashed password.
DB::table('password_resets')->where(['email'=> $request->email])->delete(); deletes the record from password_resets as the resetting was completed and the link isn't active anymore.
return redirect('/login') redirects user to Log In page to log in with a newly changed password.
web.php with routes for all of the above functions and views:
As I previously mentioned and as can be noticed on the screenshot above, the register option routes use a 'guest' middleware. Middleware
provides a convenient mechanism for inspecting and filtering HTTP
requests entering the application. Middleware routes are stated in Kernel.php file and point to the path of middleware rules and definitions.
in my application you can see me using ones like: 'auth', 'guest' or 'can'.
Developers can create their own middleware which saves the time in later development and helps with avoiding code repetition.
Komentarze
Prześlij komentarz