1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MedianetDev\LaravelAuthApi\Http\Controllers; |
4
|
|
|
|
5
|
|
|
use MedianetDev\LaravelAuthApi\Http\Helpers\ApiResponse; |
6
|
|
|
use MedianetDev\LaravelAuthApi\Http\Requests\SocialAccountRequest; |
7
|
|
|
use MedianetDev\LaravelAuthApi\Models\ApiUser; |
8
|
|
|
use MedianetDev\LaravelAuthApi\Models\LinkedSocialAccount; |
9
|
|
|
|
10
|
|
|
class LinkedSocialAccountController extends Controller |
11
|
|
|
{ |
12
|
2 |
|
public function findOrCreate(SocialAccountRequest $request) |
13
|
|
|
{ |
14
|
|
|
// see if any social account with the given data exists |
15
|
2 |
|
$socialAccount = $this->getSocialAccount($request); |
16
|
|
|
|
17
|
|
|
// if there is a social account return the associated user and the access token |
18
|
2 |
|
if ($socialAccount) { |
19
|
|
|
return ApiResponse::send([ |
20
|
|
|
'flag' => 0, |
21
|
|
|
'user' => $socialAccount->user, |
22
|
|
|
'access_token' => $socialAccount->user->createToken('AppName')->accessToken, |
23
|
|
|
], 1, 200, "find an associated user account with this $request->provider_name account"); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
// try to get a user with the given email address |
27
|
2 |
|
$user = ApiUser::where('email', $request->email)->first(); |
28
|
|
|
|
29
|
|
|
// if there is no user with that email address create one |
30
|
2 |
|
$newUser = false; |
31
|
2 |
|
if (! $user) { |
32
|
1 |
|
$user = ApiUser::create($request->only( |
33
|
1 |
|
array_merge(['name', 'email'], array_keys(config('laravel-auth-api.extra_columns'))) |
34
|
|
|
)); |
35
|
1 |
|
$newUser = true; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
// create and link a social account |
39
|
2 |
|
$user->linkedSocialAccounts()->create($request->only(['provider_name', 'provider_id', 'email'])); |
40
|
|
|
|
41
|
|
|
// return the new created user and the access token |
42
|
2 |
|
if ($newUser) { |
43
|
1 |
|
return ApiResponse::send([ |
44
|
1 |
|
'flag' => 1, |
45
|
1 |
|
'user' => $user, |
46
|
1 |
|
'access_token' => $user->createToken('AppName')->accessToken, |
47
|
1 |
|
], 1, 201, 'new user account and social account has been created.'); |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
return ApiResponse::send([ |
51
|
1 |
|
'flag' => 0, |
52
|
1 |
|
'user' => $user, |
53
|
1 |
|
'access_token' => $user->createToken('AppName')->accessToken, |
54
|
1 |
|
], 1, 201, "new social account has been created for $request->name."); |
55
|
|
|
} |
56
|
|
|
|
57
|
2 |
|
private function getSocialAccount(SocialAccountRequest $request) |
58
|
|
|
{ |
59
|
2 |
|
return LinkedSocialAccount::where('provider_name', $request->provider_name) |
60
|
2 |
|
->where('provider_id', $request->provider_id) |
61
|
2 |
|
->first(); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|