Creating My first Api Using $Git -3 [Coding Signup, Login, and Logout Function]

Today, we will be completing the signup, login, and logout functions in our API Laravel project. I faced a few issues while coding these functions but I am glad I was able to overcome all.

In this post, I will explain to us how to write the actual signup, login and logout function that was defined in my previous post. Not only that, but I will also show us how to authorize a user to view a private message in one of the API(s) endpoints.

Signup Function

After the coded signup function in my previous post, whenever the signup function is accessed, it prints signup EndPoint Requested.

public function signup(){
echo"signup EndPoint Requested";
}

Now, we have to delete everything inside the signup function to actually write a function for our database to accept new users.

  • Firstly, we have to include these parameters inside the signup function signup(Request $request)

  • To successfully get a user registered, the user's name, email, password, and a confirmation password would be required,

$this->validate($request, [
'name' => 'required|min:4',
'email' => 'required|email',
'password' => 'required|min:8',
]);

  • Now, we'll let the $user class accept new user this way and the password encrypted.

$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);

  • During registration, each user would be given a unique token which would later be used to access hidden messages or access private APIs endpoints.

token = $user->createToken('LaravelAuthApp')->accessToken;

    return response()->json(['token' => $token], 200);

And that's all for the signup function. Below is the complete codes.

Complete Signup codes

public function signup(Request $request)
{
$this->validate($request, [
'name' => 'required|min:4',
'email' => 'required|email',
'password' => 'required|min:8',
]);

    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password)
    ]);

    $token = $user->createToken('LaravelAuthApp')->accessToken;

    return response()->json(['token' => $token], 200);
}

Login Function

So after a user has been registered successfully, the Login function needs the user's email and password to login. Meanwhile, the login function in my previous post only prints Login EndPoint Requested.

Make sure to delete everything inside the login function just as we did for the Signup function. Also, our login function would require the request parameter. so, let's include it Login(Request $request).

  • Since the login will require the registered user's email and password, this is why we declared a variable $data to hold the two values.

$data = [
'email' => $request->email,
'password' => $request->password
];

  • The last code inside the login function will be the code to compare if the data supplied to login is the same as the data provided during sign up. If the data provided is the same, the user's token would be printed out and if not, it prints an Unauthorised
   if (auth()->attempt($data)) {
        $token = auth()->user()->createToken('LaravelAuthApp')->accessToken;
        return response()->json(['token' => $token], 200);
    } else {
        return response()->json(['error' => 'Unauthorised'], 401);
    }

Complete Login codes

public function login(Request $request)
{
$data = [
'email' => $request->email,
'password' => $request->password
];

    if (auth()->attempt($data)) {
        $token = auth()->user()->createToken('LaravelAuthApp')->accessToken;
        return response()->json(['token' => $token], 200);
    } else {
        return response()->json(['error' => 'Unauthorised'], 401);
    }
}

Testing The SignUp and Login Function

Now, access http://127.0.0.1:8000/api/auth/signup with postman. Click on Body, then click on Form-data. fill in the data needed to get a user registered which are;

  • name
  • email
  • password
  • password_confirmation
    Then click on send. You will get a message that the user is registered.

image.png

Trying to login is simple. Head to http://127.0.0.1:8000/api/auth/login then supply the form with just email and password then hit enter.

image.png

I was provided with a token.

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNWRjNTFkZWMwOWI5NjQ5ZDQwM2EzNTU0YTE0MDQ4MTI1ODhlZDZiODkwYTk3OWVmMjU2NjM3NWNjYTU5YzM4YTk4OWQwZDUxOWI0NTljNmMiLCJpYXQiOjE2MDMxMzg2MTgsIm5iZiI6MTYwMzEzODYxOCwiZXhwIjoxNjM0Njc0NjE4LCJzdWIiOiIyMSIsInNjb3BlcyI6W119.b9eQ-sXPEQpbIsfMgWpo6rjqaYzxlvkPNJ9vjxHugIBKKAsIwk4oR8xUtSoR8ApCW2XRA_y29uAb0sa7QwuyPMsJOhPWU7UTrArlcG9tDqM4U-EkpC23AijcCl7BdB8hMmhEpoOC6qOlX5FVD7r-KgQDh9kAqHUWwcRAk7b6ij_TZDHJkh9JVlItelVBJcAiw5Jjp4QrN4f6BRiNhpLKdzPVyTlXvBdYShHnJd7XywWKbpBGaNpc5twCdtYeMk4DnFXBYuvFFw2FyOSmiF9bdfBwaJbue_ZKhr_VeE9rwmfrE5CBMMCN3LdfOKuoSoi5hDsim2fJaTCPl7yFnAujWTRebq1T4HCASZ7-ozGNrVgLUjKNB-xzE8EiQmi-E_nUTQP1u5cyUviv3x-e8i1Cfsn3pP6FM1EFFfyZT3-jD2fx2Z4erU4ZzhVr9o3-QcpObduJHxatWqHVpkrtZMoYO397UDmDVhwkpFmCfT7Etr9Bmn8UPFyEp8tks9RshwXjSI8zxGSTO5z_UojX-_qujehHZ1LAaNMaAXYMuw7py602uqLw5jJ69tDZZk9y1lcXv0ZpyAtet-7pCMHfjro4KkRefsZb3r68z8HnRQRKU0QlXGUZfxLiugNR5Hf-zbLNol6SxoefYZBh2JEbJgMkiGunolMze0obSr8q7wV41A0

Now our signup and login function is working as expected, let's write a function and create a controller to point to the function. I will also use middleware to protect this function so that a user would need to be logged in to access the message.
Here's the controller code

Route::middleware('auth:api')->get('message', [AuthController::class, 'message']);

Here's a function that displays all users in my database. to view this the users, we'll need to access this API with the user token provided above.

function message(){
        return User::all();
    }

Accessing this URL http://127.0.0.1:8000/api/auth/message
will require us to insert the user's token and after we do, a list of users would be shown.

image.png

Logout funtion

To logout a user, we have to add this code inside our route API;

Route::middleware('auth:api')->post('logout', [AuthController::class, 'logout']);
 

This code is pointing to a logout function inside the AuthController PHP file. Below is the complete code of how the logout function looks like;

public function logout(Request $request){
        $request->user()->token()->revoke(); 
        return response()->json([
            "message"=>"User logged out successfully"
        ], 200);
    }

Testing Logout Function

Since we've successfully tested our login function, this means that the user is logged in already, now, let's hit the logout API to log the user out.

That's all for this post guys. We've been able to complete our Signup, Login, and Logout functions.

H2
H3
H4
3 columns
2 columns
1 column
3 Comments
Ecency