Completed
Push — master ( f9b5c2...696661 )
by Pásztor
02:03
created

AuthController::user()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Autumn\JWTAuth\Http\Controllers;
4
5
use Validator;
6
use Tymon\JWTAuth\JWTAuth;
7
use Illuminate\Http\Request;
8
use RainLab\User\Models\User;
9
use Tymon\JWTAuth\Exceptions\JWTException;
10
use Illuminate\Routing\Controller as BaseController;
11
12
class AuthController extends BaseController
13
{
14
    protected $auth;
15
16
    public function __construct(JWTAuth $auth)
17
    {
18
        $this->auth = $auth;
19
    }
20
21
    public function authenticate(Request $request)
22
    {
23
        try {
24
            if (! $token = $this->auth->attempt($request->only('email', 'password'))) {
25
                return response()->json([
26
                    'error' => 'invalid_credentials',
27
                ], 401);
28
            }
29
        } catch (JWTException $e) {
30
            return response()->json([
31
                'error' => 'could_not_create_token',
32
            ], $e->getStatusCode());
33
        }
34
35
        return response()->json(compact('token'));
36
    }
37
38
    public function register(Request $request)
39
    {
40
        $data = $request->all();
41
42
        if (! array_key_exists('password_confirmation', $request->all())) {
43
            $data['password_confirmation'] = $request->get('password');
44
        }
45
46
        $validator = $this->validator($data);
47
48
        if ($validator->fails()) {
49
            return response()->json([
50
                'error' => $validator->getMessageBag(),
51
            ], 400);
52
        }
53
54
        $user = User::create($data);
55
        $token = $this->auth->attempt($request->only('email', 'password'));
56
57
        return response()->json(compact('user', 'token'));
58
    }
59
60
    public function user(Request $request)
61
    {
62
        $user = $request->user();
63
64
        return response()->json(compact('user'));
65
    }
66
67
    public function logout()
68
    {
69
        $this->auth->invalidate($this->auth->getToken());
70
71
        return response(null, 200);
72
    }
73
74
    /**
75
     * Get a validator for an incoming registration request.
76
     *
77
     * @param array $data
78
     *
79
     * @return \Illuminate\Contracts\Validation\Validator
80
     */
81
    protected function validator(array $data)
82
    {
83
        return Validator::make($data, [
84
            'username' => 'required|between:3,64|unique:users',
85
            'email' => 'required|between:3,64|email|unique:users',
86
            'password' => 'required|between:4,64|confirmed',
87
        ]);
88
    }
89
}
90