1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CodexShaper\DBM\Http\Controllers; |
4
|
|
|
|
5
|
|
|
use CodexShaper\DBM\Facades\Manager as DBM; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use Illuminate\Support\Facades\Auth; |
8
|
|
|
use Illuminate\Support\Facades\Config; |
9
|
|
|
use Illuminate\Support\Facades\Response; |
10
|
|
|
use Illuminate\Support\Facades\Validator; |
11
|
|
|
|
12
|
|
|
class UserController extends Controller |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Show login form |
16
|
|
|
* |
17
|
|
|
* @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory |
18
|
|
|
*/ |
19
|
|
|
public function showLoginForm() |
20
|
|
|
{ |
21
|
|
|
return view('dbm::admin'); |
22
|
|
|
} |
23
|
|
|
/** |
24
|
|
|
* Login User for API |
25
|
|
|
* |
26
|
|
|
* @return \Illuminate\Http\JsonResponse |
27
|
|
|
*/ |
28
|
|
|
public function login(Request $request) |
29
|
|
|
{ |
30
|
|
|
if ($request->ajax()) { |
31
|
|
|
try { |
32
|
|
|
$validator = Validator::make($request->data, [ |
33
|
|
|
'email' => 'required|email', |
34
|
|
|
'password' => 'required', |
35
|
|
|
|
36
|
|
|
]); |
37
|
|
|
|
38
|
|
|
if ($validator->fails()) { |
39
|
|
|
$errors = []; |
40
|
|
|
foreach ($validator->errors()->all() as $error) { |
41
|
|
|
$errors[] = $error; |
42
|
|
|
} |
43
|
|
|
return $this->generateError($errors); |
44
|
|
|
} |
45
|
|
|
$credentials = [ |
46
|
|
|
'email' => $request->data['email'], |
47
|
|
|
'password' => $request->data['password'], |
48
|
|
|
]; |
49
|
|
|
|
50
|
|
|
if (!Auth::attempt($credentials)) { |
51
|
|
|
return $this->generateError(["Email and password combination doesn't match"]); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$user = Auth::user(); |
55
|
|
|
$expiry = Config::get('dbm.auth.token.expiry'); |
56
|
|
|
if (count($user->tokens) > 0) { |
|
|
|
|
57
|
|
|
$user->tokens()->delete(); |
58
|
|
|
} |
59
|
|
|
return response()->json([ |
60
|
|
|
'success' => true, |
61
|
|
|
'user' => $user, |
62
|
|
|
'token' => $user->createToken('DBM')->accessToken, |
63
|
|
|
'expiry' => $expiry, |
64
|
|
|
]); |
65
|
|
|
|
66
|
|
|
} catch (\Exception $e) { |
67
|
|
|
$this->generateError([$e->getMessage()]); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
return response()->json(["success" => false, "error" => "Unauthorised"], 401); |
71
|
|
|
|
72
|
|
|
} |
73
|
|
|
/** |
74
|
|
|
* Generate errors and return response |
75
|
|
|
* |
76
|
|
|
* @param array $errors |
77
|
|
|
* |
78
|
|
|
* @return \Illuminate\Http\JsonResponse |
79
|
|
|
*/ |
80
|
|
|
public function generateError($errors) |
81
|
|
|
{ |
82
|
|
|
return response()->json([ |
83
|
|
|
'success' => false, |
84
|
|
|
'errors' => $errors, |
85
|
|
|
], 400); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|