· 6 years ago · Feb 11, 2019, 12:26 PM
1<?php
2
3namespace App\Http\Controllers\Auth;
4
5use App;
6use Request;
7use App\Notifications\SignupActivate;
8use Illuminate\Http\Request as Req;
9
10use Laravel\Passport\Bridge\AccessToken;
11use Laravel\Passport\Bridge\AccessTokenRepository;
12use Laravel\Passport\Bridge\Client;
13use Laravel\Passport\Bridge\Scope;
14use Laravel\Passport\TokenRepository;
15use League\OAuth2\Server\CryptKey;
16
17use App\Exceptions\AuthenticationException;
18use Psr\Http\Message\ServerRequestInterface;
19use App\Http\Model\Store;
20use App\Exceptions\DataEmptyException;
21use Laravel\Passport\Http\Controllers\AccessTokenController;
22
23class CustomAccessTokenController extends AccessTokenController
24{
25
26 /**
27 * Hooks in before the AccessTokenController issues a token
28 *
29 *
30 * @param ServerRequestInterface $request
31 * @return mixed
32 */
33 public function issueUserToken(ServerRequestInterface $request)
34 {
35 $httpRequest = request();
36 if ($httpRequest->grant_type == 'password') {
37 $tokenResponse = parent::issueToken($request);
38 $token = $tokenResponse->getContent();
39
40 // $tokenInfo will contain the usual Laravel Passort token response.
41 $tokenInfo = json_decode($token, true);
42
43 $username = $request->getParsedBody()['username'];
44 $user = \App\Http\Model\User::whereEmail($username)->first();
45
46 if(!$user){
47 return response()->json([
48 "error" =>"invalid_credentials",
49 "message" => "The user credentials were incorrect."
50 ], 401);
51 }
52
53 $tokenInfo = collect($tokenInfo);
54 $tokenInfo->put('user', $user);
55
56 #custom for save token devices after get token login------------------------------------------------
57 if (\Illuminate\Support\Facades\Schema::hasTable('ci_store_token_devices') && !empty(\Request::input('token_fcm')))
58 {
59 \DB::beginTransaction();
60 try{
61
62 $getToko = \App\Http\Model\StoreUsers::where('user_id', $tokenInfo['user']->id)->get();
63 foreach($getToko as $toko){
64 $saveTokenDevice = \App\Http\Model\TokenDevice::firstOrNew([
65 'device_store_id' => $toko->store_id,
66 'token_device' =>\Request::input('token_fcm'),
67 ]);
68
69 $saveTokenDevice->user_id = $tokenInfo['user']->id;
70 $saveTokenDevice->device_store_id = $toko->store_id;
71 $saveTokenDevice->token_device = \Request::input('token_fcm');
72 $saveTokenDevice->login_status = 1;
73 $saveTokenDevice->active = 0;
74 $saveTokenDevice->last_activity = \DB::raw('now()');
75 $saveTokenDevice->save();
76 }
77
78 \DB::commit();
79 }catch(\Exception $e){
80 \DB::rollBack();
81 return $e;
82 }
83 }
84 #end custom for save token devices after get token login--------------------------------------------
85 // return $tokenInfo;
86 return $tokenResponse;
87 }
88 }
89
90 public function logoutApi()
91 {
92 if (auth()->guard('api')->check()) {
93 auth()->guard('api')->user()->getAccessToken()->delete();
94
95 if (\Illuminate\Support\Facades\Schema::hasTable('ci_store_token_devices'))
96 {
97 $cektoken = \App\Http\Model\TokenDevice::select('token_device')->where(['device_store_id' => \Config::get('sitesetting.store')->id, 'login_status' => '1'])->first();
98 \DB::beginTransaction();
99 try{
100 \App\Http\Model\TokenDevice::where([
101 // 'device_store_id' => \Config::get('sitesetting.store')->id,
102 'token_device' => $cektoken->token_device,
103 'login_status' => 1
104 ])
105 ->update([
106 'last_activity' => \DB::raw('now()'),
107 'active' => 0,
108 'login_status' => 0,
109 ]);
110 \DB::commit();
111 }catch(\Exception $e){
112 \DB::rollBack();
113 }
114 }
115
116 return \Response::json(
117 [
118 'message' => 'Success',
119 'status_code' => 200,
120 'error' => 'Success Logout',
121 ],
122 200);
123 }
124
125 return \Response::json(
126 [
127 'message' => 'Failed',
128 'status_code' => 401,
129 'error' => 'authentication check failed',
130 ],
131 401);
132 }
133
134 public function register(Req $request)
135 {
136 $data = $request->only('email','name','password','password_confirmation','phone','name_toko','url_id','business_type_id','service_type_id','pos_resto_mode','country_id','state_id','city_id','partner_id','i_agree');
137
138 $valid = validator($data, [
139 'name' => 'required|string|max:255',
140 'email' => 'required|string|email|max:255|unique:ci_user',
141 'password' => 'required|string|min:6',
142 'password_confirmation' => 'required_with:password|same:password|min:6',
143 'phone' => 'required',
144 'name_toko' => 'required',
145 'business_type_id' => 'required',
146 'url_id' => 'required',
147 'country_id' => 'required',
148 'state_id' => 'required',
149 'city_id' => 'required',
150 ]);
151
152 if ($valid->fails()) {
153 return \Response::json(
154 [
155 'error' => [
156 'store'=> null,
157 'message' => 'Error Found',
158 'status_code' => 400,
159 "error"=> $valid->errors()->first(),
160 ]
161 ], 400);
162
163 }
164
165 \DB::beginTransaction();
166 if(empty($data['i_agree'])) throw new DataEmptyException(trans('validation.agree'));
167
168 $user = \App\User::create([
169 'name' => $data['name'],
170 'email' => $data['email'],
171 'password' => bcrypt($data['password']),
172 'mobile' => $data['phone'],
173 'status' => 'A',
174 'verified' => 0,
175 'verify_token' => str_random(60)
176 ]);
177
178 $store = Store::whereRaw("url_id = ?", array($data['url_id']))->first();
179 if($store) throw new DataEmptyException(trans('validation.unique', array('attribute'=>'url_id')));
180
181 if(empty($data['service_type_id'])){
182 $expiry_date = date('Y-m-d', strtotime("+14 days"));
183 $pos_expiry_date = date('Y-m-d', strtotime("+14 days"));
184 }
185
186 if(in_array($data['service_type_id'], [1,3])){
187 $expiry_date = date('Y-m-d', strtotime("+14 days"));
188 $pos_expiry_date = date('Y-m-d', strtotime("+14 days"));
189 }
190
191 $pos_resto_mode = 0;
192 if(in_array($data['service_type_id'], [2,3])){
193 $pos_expiry_date = date('Y-m-d', strtotime("+14 days"));
194 if(!empty($data['pos_resto_mode'])){
195 $pos_resto_mode = $data['pos_resto_mode'];
196 }
197 }
198
199 $country = \App\Http\Model\Country::find($data['country_id']);
200
201 $createStore = \App\Http\Model\Store::create([
202 'name' => $data['name_toko'],
203 'url_id' => strtolower($data['url_id']),
204 'business_type_id' => $data['business_type_id'],
205 'plan_type_id' => \Config::get('sitesetting.defaultplantypeid'),
206 'country_id' => $data['country_id'],
207 'city_id' => $data['city_id'],
208 'currency_id' => $country->currency_id,
209 'email' => $data['email'],
210 'shipping_calc_type_id' => 'A',
211 'website_published' => true,
212 'pos_published' => true,
213 'website_lang_code' => $country->lang_code,
214 'expiry_date' => $expiry_date,
215 'pos_expiry_date' => $pos_expiry_date,
216 'pos_resto_mode' => $pos_resto_mode,
217 'lang_code' => $country->lang_code,
218 'partner_id' =>!empty($data['partner_id'])?$data['partner_id']:NULL,
219 'theme_id' => \Config::get('sitesetting.defaultthemeid'),
220 'theme_layout_mode' => \Config::get('sitesetting.defaultthemelayout'),
221 'theme_color' => \Config::get('sitesetting.defaultthemecolor'),
222 'status' => 'A',
223 ]);
224
225 $createStore->users()->attach($user->id, array('role_id' => 'OW'));
226
227 $user = \App\User::find($user->id);
228 $user->notify(new SignupActivate($user));
229
230 // // And created user until here.
231 // // $client = Client::where('password_client', 1)->first();
232 // $client = \DB::table('oauth_clients')->where('password_client', 1)->first();
233 // $client = json_decode(json_encode($client, false), true);
234
235 // if (empty($client)) {
236 // // throw new AuthenticationException(trans('users.error_allocating_token'));
237 // throw new AuthenticationException();
238 // }
239
240 // // Is this $request the same request? I mean Request $request? Then wouldn't it mess the other $request stuff? Also how did you pass it on the $request in $proxy? Wouldn't Request::create() just create a new thing?
241
242 // $request->request->add([
243 // 'grant_type' => 'password',
244 // 'client_id' => $client['id'],
245 // 'client_secret' => $client['secret'],
246 // 'username' => $data['email'],
247 // 'password' => $data['password'],
248 // 'scope' => null,
249 // ]);
250
251
252 // // Fire off the internal request.
253 // $token = Request::create(
254 // 'oauth/token',
255 // 'POST'
256 // );
257
258
259 // $data['store_name'] = $data['name_toko'];
260 // $data['store_url_id'] = $data['url_id'];
261 // $data['lang_code'] = $country->lang_code;
262 // \Mail::send('storefront.mail.newstore', $data, function($message) use ($data)
263 // {
264 // \App::setLocale($data['lang_code']);
265 // $message->to($data['email'], $data['name'])->subject(trans('storefront/email.new_store_added', array('name' => $data['name_toko'])));
266 // });
267
268 \DB::commit();
269
270 return \Response::json(
271 [
272 'message' => 'Registration succesfully.',
273 'status_code' => 200,
274 'error' => 0,
275 ],
276 200);
277
278
279 // return \Route::dispatch($token);
280
281 }
282
283 public function signupActivate($token)
284 {
285 \DB::beginTransaction();
286 $user = \App\Http\Model\User::where('verify_token', $token)->first();
287 if (!$user) {
288 return response()->json(
289 [
290 'error' => [
291 'store'=> null,
292 'message' => 'Error Found',
293 'status_code' => 400,
294 "error"=> 'This activation token is invalid',
295 ]
296 ], 400);
297 }
298 $user->verified = 1;
299 $user->verify_token = '';
300 $user->save();
301
302 \DB::commit();
303
304 if ($request->wantsJson()) {
305 return response()->json(
306 [
307 'message' => 'Success Activated.',
308 'status_code' => 200,
309 "error"=> 0,
310 ], 200);
311 }
312 }
313
314}