Skip to content

Commit

Permalink
User Authentication and Authorization APIs;
Browse files Browse the repository at this point in the history
  • Loading branch information
IrakozeLoraine committed Feb 26, 2021
1 parent eda714f commit c61e8dd
Show file tree
Hide file tree
Showing 10 changed files with 814 additions and 16 deletions.
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,5 @@ PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

JWT_SECRET=fXbyavSqHw4QgmdUeT0o3OeVMvWYHcjaB3mU4sVwFqTHq9ojXRlsE5vroJxxO29a
136 changes: 136 additions & 0 deletions app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Validator;


class UserController extends Controller
{
/**
* Create a new UserController instance.
*
* @return void
*/

public function _construct(){
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}

/**
* Register a User.
*
* @return \Illuminate\Http\JsonResponse
*/

public function register(Request $request) {
/**
* Validate user inputs
*
* @return \Illuminate\Http\JsonResponse
*/

$validator = Validator::make($request->all(), [
'first_name' => 'required|string|between:3,255',
'last_name' => 'required|string|between:3,255',
'username' => 'required|string|between:3,255',
'email' => 'required|string|email|max:255|unique:users',
'phone_number' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
'password' => 'required|string|confirmed|min:8',
]);

if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}

$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));

return response()->json([
'message' => 'User registered successfully',
'user' => $user
], 201);
}

/**
* Get a JWT via provided credentials for login.
*
* @return \Illuminate\Http\JsonResponse
*/

public function login(Request $request){
/**
* Validate user inputs
*
* @return \Illuminate\Http\JsonResponse
*/
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:8'
]);

if($validator->fails()){
return response()->json($validator->errors(), 422);
}

if(!$token = auth('api')->attempt($validator->validate())){
return response()->json(['error' => 'Unauthorized'], 401);
}

return $this->createNewToken($token);
}

/**
* Get the authenticated User
*
* @return \Illuminate\Http|JsonResponse
*/
public function currentUser(){
return response()->json(auth()->user());
}

/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/

public function logout(){
auth()->logout();

return response()->json(['message' => 'User successfully signed out']);
}

/**
* Refresh a token
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh(){
return $this->createNewToken(auth()->refresh());
}

/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token){
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60,
'user' => auth()->user()
]);


}
}
42 changes: 38 additions & 4 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,36 @@

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable
class User extends Eloquent implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract, JWTSubject
{
use HasFactory, Notifiable;
use Authenticatable, Authorizable, CanResetPassword, HasFactory, Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'first_name',
'last_name',
'username',
'email',
'phone_number',
'password',
'profile_picture',
'status'
];

/**
Expand All @@ -29,6 +43,7 @@ class User extends Authenticatable
*/
protected $hidden = [
'password',
'status',
'remember_token',
];

Expand All @@ -40,4 +55,23 @@ class User extends Authenticatable
protected $casts = [
'email_verified_at' => 'datetime',
];

/**
* Get the identifier that will be stored in the subject claim of the JWT
*
* @return mixed
*/
public function getJWTIdentifier(){
return $this->getKey();
}

/**
* Return a key value array, containing any custom claims to be added to the JWT
*
* @return array
*/
public function getJWTCustomClaims(){
return [];
}

}
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@
"license": "MIT",
"require": {
"php": "^7.3|^8.0",
"ext-json": "*",
"fideloper/proxy": "^4.4",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1",
"jenssegers/mongodb": "^3.8",
"laravel/framework": "^8.12",
"laravel/telescope": "^4.4",
"laravel/tinker": "^2.5",
"ext-json": "*"
"tymon/jwt-auth": "dev-develop#34d8e48 as 1.0.0-rc.3.2"
},
"require-dev": {
"facade/ignition": "^2.5",
Expand Down
Loading

0 comments on commit c61e8dd

Please sign in to comment.