Completed
Push — master ( 9afc05...393be9 )
by Pásztor
06:31
created

AuthController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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 Illuminate\Routing\Controller as BaseController;
10
use Tymon\JWTAuth\Exceptions\JWTException;
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
    /**
61
     * Get a validator for an incoming registration request.
62
     *
63
     * @param array $data
64
     *
65
     * @return \Illuminate\Contracts\Validation\Validator
66
     */
67
    protected function validator(array $data)
68
    {
69
        return Validator::make($data, [
70
            'username' => 'required|between:3,64|unique:users',
71
            'email'    => 'required|between:3,64|email|unique:users',
72
            'password' => 'required|between:4,64|confirmed',
73
        ]);
74
    }
75
}
76