aboutsummaryrefslogtreecommitdiff
path: root/src/CamilStaps/BotleaguesApi/TokenAuthenticationProvider.php
blob: 053f8377840af3a69c5d23f3647dcbe4227f8504 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
/**
 * Created by PhpStorm.
 * User: camilstaps
 * Date: 12-5-15
 * Time: 14:41
 */

namespace CamilStaps\BotleaguesApi;

use Dingo\Api\Auth\ProviderInterface;
use Dingo\Api\Routing\Route;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class TokenAuthenticationProvider implements ProviderInterface {

    /**
     * Authenticate the request and return the authenticated user instance.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Dingo\Api\Routing\Route $route
     *
     * @return mixed
     */
    public function authenticate(Request $request, Route $route) {
        if (!$request->has(['user_id', 'token'])) {
            throw new UnauthorizedHttpException(null, "Include user_id and token in your request.");
        }

        $user = User::find($request->get('user_id'));
        if ($user != null && $user->validToken($request->get('token'))) {
            Auth::login($user);
            return Auth::user();
        }

        throw new UnauthorizedHttpException(null, "Invalid credentials");
    }

    /**
     * Get the providers authorization method.
     *
     * @return string
     */
    public function getAuthorizationMethod() {
        return 'token';
    }
}