Inheritance: extends Illuminate\Database\Eloquent\Model
 public function add()
 {
     $className = '\\App\\Library\\' . $this->provider_value . 'Interface';
     $objInterface = new $className();
     $query = User::find(Auth::user()->id)->token->where("provider", $this->provider_id);
     $connection_email = $objInterface->getAccountInfo()->email;
     $have_connection = false;
     foreach ($query as $val) {
         if ($connection_email == $val->connection_email) {
             $have_connection = true;
             break;
         }
     }
     if ($have_connection) {
         $tk = User::find(Auth::user()->id)->token->where('connection_email', $connection_email)->where('provider_id', $this->provider_id)->first();
     } else {
         $gtc_folder = $objInterface->searchFile('GatherCloudForAll');
         if (empty($gtc_folder)) {
             $gtc_folder = $objInterface->uploadFile('GatherCloudForAll', null);
         }
         $gtc_folder = $objInterface->normalizeMetaData($gtc_folder, "", "");
         $connection_name = Session::get('new_connection_name');
         $tk = new Token();
         $tk->connection_name = $connection_name;
         $tk->connection_email = $connection_email;
         $tk->user_id = Auth::user()->id;
         $tk->provider_id = $this->provider_id;
         $tk->gtc_folder = $gtc_folder[0]['path'];
     }
     $tk->access_token = $objInterface->getToken()->access_token;
     $tk->expired_in = $objInterface->getToken()->expired_in;
     $tk->refresh_token = $objInterface->getToken()->refresh_token;
     $tk->save();
 }
 public static function generateToken($user)
 {
     $token = new Token();
     $token->auth_token = bin2hex(openssl_random_pseudo_bytes(16));
     $token->expires_at = (new DateTime())->add(new DateInterval('PT10M'));
     $token->user()->associate($user);
     $token->save();
     return $token->auth_token;
 }
Exemple #3
0
 public function registerEmail(Request $request, City $city)
 {
     $token = new Token();
     $token->save();
     $token->createNewToken($city);
     Mail::send('emails.registration.token', ['token' => $token, 'request' => $request, 'city' => $city], function ($m) use($token, $request, $city) {
         $m->from('*****@*****.**', 'See+Do')->to($request->email, $request->name)->subject('Here is your registration link to start contributing to See+Do in ' . $city->name . '.')->getHeaders()->addTextHeader('X-MC-Subaccount', 'see-do');
     });
     Notification::success('Registration email sent to ' . $request->name . ' at ' . $request->email);
     return redirect('/' . $city->iata . '/users');
 }
Exemple #4
0
 private static function generate($owner, $minutes, $type)
 {
     $carbon = Carbon::create();
     $carbon->addMinute($minutes);
     $token = new Token();
     $token->value = static::generateValue();
     $token->expire_in = $carbon;
     $token->owner = $owner;
     $token->type = $type;
     $token->save();
     return $token;
 }
 public function handle($request, Closure $next, $guard = null)
 {
     $setCookie = false;
     if (!$request->has('shop') && !$request->hasCookie('shopify_domain')) {
         return $next($request);
     }
     if (!$request->has('shop')) {
         $domain = $request->cookie('shopify_domain');
     } else {
         $domain = $request->input('shop');
         $setCookie = true;
     }
     $setup['SHOP_DOMAIN'] = $domain;
     $token = \App\Token::where('domain', $domain)->first();
     if ($token) {
         $setup['ACCESS_TOKEN'] = $token->token;
     }
     Sh::setup($setup);
     if ($setCookie) {
         $response = $next($request);
         $response->withCookie(cookie()->forever('shopify_domain', $domain));
         return $response;
     } else {
         return $next($request);
     }
 }
 public function login(Request $request)
 {
     $input = $request->json()->all();
     $validator = Validator::make($input, ['email' => 'required|email', 'password' => 'required', 'deviceId' => 'required']);
     if ($validator->fails()) {
         $error = $validator->errors()->all();
         return response()->json(['errorMessage' => [$error]], 404);
     }
     $deviceId = $input['deviceId'];
     $result = DB::table('users')->where('email', $input['email'])->first();
     if ($result && Hash::check($input['password'], $result->password)) {
         $res = DB::table('tokens')->where('deviceId', $deviceId)->first();
         if ($res) {
             $token = Token::find($res->id);
             $token->token = bin2hex(openssl_random_pseudo_bytes(64));
             $token->save();
         } else {
             DB::table('tokens')->insert(['token' => bin2hex(openssl_random_pseudo_bytes(64)), 'userId' => $result->id, 'deviceId' => $deviceId]);
         }
         $token = DB::table('tokens')->select('token')->where('userId', $result->id)->where('deviceId', $deviceId)->first();
         if ($token) {
             return response()->json($token);
         } else {
             return response()->json(['errorMessage' => 'login failed'], 404);
         }
     } else {
         return response()->json(['errorMessage' => 'this user not found'], 404);
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @param  Request  $request
  * @return Response
  */
 public function store(Request $request)
 {
     $device = Device::current();
     if (Input::hasFile('file')) {
         $inputFile = Input::file('file');
         $package = Package::createFromInputFile($inputFile, $device->user_id);
     } else {
         $package = Package::findOrFailFromArg(Input::get('package'), $device->user_id);
     }
     $ids = explode(',', Input::get('devices'));
     if (count($ids) == 1 && !is_numeric($ids[0])) {
         $token = Token::whereValue($ids[0])->valid()->first();
         if ($token) {
             $devices = Device::whereId($token->owner)->get();
         } else {
             return Response::error(trans('errors.expired_device_qrcode') . $ids[0], 400);
         }
     }
     if (empty($devices)) {
         $devices = Device::whereIn('id', $ids)->where(function ($query) use($device) {
             $query->whereUserId($device->user_id)->orWhere(function ($query) use($device) {
                 $authed_device_ids = DUAuth::whereUserId($device->user_id)->lists('device_id');
                 $query->whereIn('id', $authed_device_ids);
             });
         })->get();
     }
     try {
         $push = Push::send($devices, $package, $device->user_id);
         return Response::json($push);
     } catch (\Exception $e) {
         return Response::exception($e);
     }
 }
 private function start($message, $tg)
 {
     $key = trim(str_replace('/start', '', $message['text']));
     $token = Token::findByToken($key);
     $app = App::findOrFail($token->app_id);
     try {
         $auth = Auth::findByAppAndTelegramUser($app, $tg);
     } catch (ModelNotFoundException $e) {
         $auth = new Auth();
         $auth->app_id = $app->id;
         $auth->telegram_user_id = $tg->id;
         $auth->email = 'a' . $app->id . 't' . $tg->id . '-' . generate_email() . '@telegramlogin.com';
     }
     $auth->access_token = generate_access_token();
     $auth->active = true;
     $auth->save();
     $code = Code::create(array('app_id' => $app->id, 'auth_id' => $auth->id, 'code' => generate_code()));
     $url = $app->redirect_url . '?code=' . $code->code;
     if ($token->query_string) {
         $url .= '&' . $token->query_string;
     }
     $text = 'Please click this link to finish your signup at *' . $app->name . '*: ' . PHP_EOL;
     $text .= '[Click here](' . $url . ')';
     $params = array('text' => $text, 'chat_id' => $tg->telegram_id);
     $this->send($params);
     $token->delete();
     if ($app->client_id == 314159265) {
         $tg->status = str_replace('state=', '', $token->query_string);
     } else {
         $tg->status = 'access_granted';
     }
     $tg->save();
 }
Exemple #9
0
 /**
  * Create a new user instance after a valid registration.
  *
  * @param array $data
  *
  * @return User
  */
 protected function create(array $data)
 {
     $token = Token::where('token', '=', $data['registration_token'])->first();
     $city = City::where('id', '=', $token->city_id)->first();
     $user = User::create(['name_first' => $data['name_first'], 'name_last' => $data['name_last'], 'username' => $data['username'], 'bio' => $data['bio'], 'email' => $data['email'], 'password' => bcrypt($data['password']), 'city_id' => $city->id]);
     Event::fire(new PostSuccessfullAuth($data['registration_token']));
     return $user;
 }
 private function createToken($app)
 {
     try {
         $randToken = generate_token();
         return Token::create(array('app_id' => $app->id, 'token' => $randToken));
     } catch (\Exception $e) {
         return $this->createToken($app);
     }
 }
 /**
  * Authenticate the given request token is valid or not.
  *
  * @param  string $token
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function authenticate($token)
 {
     $token = Token::where('token', '=', $token)->first();
     if (is_null($token) || $token->disable) {
         $msg = is_null($token) ? 'Invalid token' : 'Application is disable';
         return response_unauthorized($msg);
     }
     return response_ok($token);
 }
Exemple #12
0
 public function generate($size = 64)
 {
     do {
         $random = '';
         for ($i = 0; $i < $size; $i++) {
             $random .= chr($this->charTab[rand(0, count($this->charTab) - 1)]);
         }
     } while (\App\Token::all()->contains('random', $random));
     return $random;
 }
Exemple #13
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $now = Carbon::now();
     foreach (Token::all() as $token) {
         $date = Carbon::parse($token->expiry_date);
         if ($now->timestamp >= $date->timestamp) {
             Token::destroy($token->id);
         }
     }
 }
 public function handle($request, Closure $next)
 {
     $authToken = $request->header('Auth-token');
     if (!$authToken || !AuthService::tokenIsValid($authToken)) {
         //return abort(401, 'Not authorized.');
         return response('Not authorized.')->header('Status', 401);
     }
     AuthService::extendToken($authToken);
     Auth::login(Token::where('auth_token', $authToken)->first()->user);
     return $next($request);
 }
 public function doPasswordReset($token)
 {
     $token = Token::where('token', '=', $token)->first();
     if ($token == null) {
         return Redirect::to('home')->with("bad", "Token expired, does not exist, or has already been used. Please check, and try again.");
     }
     $user = $token->user()->first();
     Auth::login($user);
     $token->delete();
     return view('users.edit', compact('user'))->with("good", "Successfully logged in using token - please change your password now");
 }
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     $route = app()->router->getCurrentRoute();
     $routeParam = $route->getParameter('token');
     $paramToken = Token::where('token', '=', $routeParam)->first();
     if ($paramToken) {
         return $next($request);
     } else {
         Notification::error('Your registration token has expired, please contact harry@madebyfieldwork.com for a new one');
         return redirect('/');
     }
 }
Exemple #17
0
 function __construct($connection_name)
 {
     $this->connection_name = $connection_name;
     $tk = Token::where('connection_name', $connection_name)->where('user_id', Auth::user()->id)->firstOrFail();
     $pvd = Providers::where("id", $tk->provider_id)->first();
     $this->provider_value = $pvd->reference_name;
     $this->provider_logo = $pvd->provider_logo;
     $this->owner = $tk->user_id;
     $this->token_id = $tk->id;
     $token = array('access_token' => $tk->access_token, 'expired_in' => $tk->expired_in, 'refresh_token' => $tk->refresh_token);
     $className = '\\App\\Library\\' . $this->provider_value . 'Interface';
     $this->connObj = new $className((object) $token);
 }
 /**
  * Reset the given user's password.
  *
  * @param  Request  $request
  * @return Response
  */
 public function postReset(ResetRequest $request)
 {
     $credentials = $request->only('email', 'password', 'password_confirmation', 'token');
     $email = Token::where('token', '=', $request->get('token'))->first()->email;
     $credentials['email'] = $email;
     $response = $this->reminderService->reset($credentials);
     switch ($response) {
         case PasswordBroker::PASSWORD_RESET:
             return redirect()->back()->with('status', '');
         default:
             return redirect()->back()->withErrors(['email' => trans($response)]);
     }
 }
 public static function getMostUsedApps($count = 5)
 {
     $ins = new static();
     $token_counts = Token::getAppTokenCounts();
     return array_map(function ($app) use($ins) {
         $info = $ins->where('key', $app['_id'])->first(['_id', 'name', 'key']);
         $app['id'] = $info->id;
         $app['name'] = $info->name;
         $app['key'] = $info->key;
         unset($app['_id']);
         return $app;
     }, array_slice($token_counts, 0, $count));
 }
 protected function dashboardForAdmin()
 {
     $data['user'] = $this->user;
     $data['total_users'] = User::where('role', 'user')->count();
     $data['total_token'] = Token::count();
     $data['total_admins'] = User::where('role', 'admin')->count();
     $data['total_apps'] = Application::count();
     $data['most_used_app'] = Application::getMostUsedApps();
     $data['most_active_app'] = Application::getMostActiveApps();
     $data['users'] = User::latest()->take(10)->get();
     $data['applications'] = Application::latest()->take(10)->get();
     $data['opt_app'] = Application::getAppForSelect($this->user);
     return view('dashboard.admin', $data);
 }
 /**
  * Generate the token for given api key.
  *
  * @param  string $key
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function generate($key)
 {
     $app = Application::where('key', '=', $key)->first();
     if (is_null($app) || $app->disable) {
         $msg = is_null($app) ? 'Invalid app key' : 'Application is disable';
         return response_unauthorized($msg);
     }
     $tokenValue = $this->getUUID5Token($app);
     if ($tokenValue) {
         $token = new Token();
         $token->app_id = $app->id;
         // Application ID
         $token->app_key = $app->key;
         // Application Key
         $token->user_id = $app->user_id;
         // Application owner id
         $token->token = $tokenValue;
         // Token for unique user.
         if ($token->save()) {
             return response_ok($token);
         }
     }
     return response_error('Error occured to generate token. Please try again');
 }
 function __construct($token = null)
 {
     if ($token != null) {
         $this->access_token = $token->access_token;
         $this->refresh_token = $token->refresh_token;
         $this->expired_in = $token->expired_in;
         if ($this->getAccessTokenStatus() != 1) {
             $keyValueStore = new KeyValueStore(new MemoryAdapter());
             $keyValueStore->set('access_token', $this->access_token);
             $keyValueStore->set('refresh_token', $this->refresh_token);
             $keyValueStore->expire('access_token', 0);
             $keyValueStore->expire('refresh_token', $this->expired_in + (5184000 - 3600) - time());
             #  60 days
             $oAuthClient = new OAuthClient($keyValueStore, $this->clientId, $this->clientSecret, $this->redirectUri);
             $oAuthClient->authorize();
             $keyValueStore = $oAuthClient->getKvs();
             Token::where('access_token', $this->access_token)->where('refresh_token', $this->refresh_token)->update(array('access_token' => $keyValueStore->get('access_token'), 'refresh_token' => $keyValueStore->get('refresh_token'), 'expired_in' => time() + $keyValueStore->getTtl('access_token')));
             $this->access_token = $keyValueStore->get('access_token');
             $this->refresh_token = $keyValueStore->get('refresh_token');
             $this->expired_in = time() + $keyValueStore->getTtl('access_token');
         }
     } else {
         $keyValueStore = new KeyValueStore(new MemoryAdapter());
         $oAuthClient = new OAuthClient($keyValueStore, $this->clientId, $this->clientSecret, $this->redirectUri);
         try {
             $oAuthClient->authorize();
             $keyValueStore = $oAuthClient->getKvs();
             $this->access_token = $keyValueStore->get('access_token');
             $this->refresh_token = $keyValueStore->get('refresh_token');
             $this->expired_in = time() + $keyValueStore->getTtl('access_token');
         } catch (ExitException $e) {
             # Location header has set (box's authorize page)
             # Instead of an exit call it throws an ExitException
             exit;
         } catch (OAuthException $e) {
             # e.g. Invalid user credentials
             # e.g. The user denied access to your application
         } catch (ClientException $e) {
             # e.g. if $_GET['code'] is older than 30 sec
         }
     }
     $this->state = (object) array('redirect_uri' => null, 'token' => null);
     $this->state->token = (object) array('obtained' => null, 'data' => (object) array('access_token' => $this->access_token));
 }
 function __construct($token = null)
 {
     $this->client = new Google_Client();
     $this->client->setClientId($this->client_id);
     $this->client->setClientSecret($this->client_secret);
     $this->client->setRedirectUri($this->redirect_uri);
     $this->client->setApprovalPrompt('force');
     $this->client->setAccessType("offline");
     $this->client->addScope("https://www.googleapis.com/auth/drive");
     if ($token != null) {
         $this->access_token = $token->access_token;
         $this->refresh_token = $token->refresh_token;
         $this->expired_in = $token->expired_in;
         if ($this->getAccessTokenStatus() != 1) {
             $this->client->refreshToken($this->refresh_token);
             $token = $this->client->getAccessToken();
             $token = (array) json_decode($token);
             $this->expired_in = time() + $token['expires_in'];
             Token::where('access_token', $this->access_token)->where('refresh_token', $this->refresh_token)->update(array('access_token' => $token['access_token'], 'expired_in' => $this->expired_in));
             $this->access_token = $token['access_token'];
         } else {
             $this->client->setAccessToken(json_encode($token));
         }
         $this->drive_service = new Google_Service_Drive($this->client);
     } else {
         if (isset($_GET['code'])) {
             $this->client->authenticate($_GET['code']);
             $token = $this->client->getAccessToken();
             $token = (array) json_decode($token);
             $this->access_token = $token['access_token'];
             $this->refresh_token = $token['refresh_token'];
             $this->expired_in = time() + $token['expires_in'];
             $this->drive_service = new Google_Service_Drive($this->client);
         } else {
             $authUrl = $this->client->createAuthUrl();
             header('Location: ' . $authUrl);
             die;
         }
     }
 }
 /**
  * Boot the authentication services for the application.
  *
  * @return void
  */
 public function boot()
 {
     // Here you may define how you wish users to be authenticated for your Lumen
     // application. The callback which receives the incoming request instance
     // should return either a User instance or null. You're free to obtain
     // the User instance via an API token or any other method necessary.
     $user = null;
     $this->app['auth']->viaRequest('api', function ($request) {
         if ($request->header("AuthToken")) {
             $tk = Token::where('api_token', $request->header("AuthToken"))->first();
             return User::where('id', $tk->user_id)->first();
         }
     });
     // Authorises the current user for particular requests
     Gate::define('getUser', function ($user, $userid) {
         // TODO allow user to get users matched with them
         return $user->id == $userid;
     });
     Gate::define('deleteUser', function ($user, $userid) {
         // TODO allow user to get users matched with them
         return $user->id == $userid;
     });
 }
Exemple #25
0
 protected function generateToken($user)
 {
     $random = Token::generate();
     return \App\Token::create(['random' => $random, 'user_id' => $user->id, 'expiry_date' => Carbon::now()->addDay(7)]);
 }
Exemple #26
0
 /**
  * Handle the event.
  *
  * @param  PostSuccessfullAuth  $event
  * @return void
  */
 public function handle(PostSuccessfullAuth $event)
 {
     $storedToken = Token::where('token', '=', $event->token)->first();
     $storedToken->delete();
     Notification::success('Registration successful, welcome to See+Do');
 }
 public function selectIn()
 {
     if (Auth::check()) {
         $id = $_GET['connection_name'];
         $any = $_GET['path'];
         $cname = 'all';
         $proObj = new Provider($id);
         $data = $proObj->getFiles($any);
         // dummy check
         $dummy_tk = Token::where('connection_name', $id)->where('user_id', Auth::user()->id)->firstOrFail();
         $dummy_files = DummyFile::where('dummy_store', $dummy_tk->id)->where('dummy_path', $any)->get();
         if (!empty($dummy_files)) {
             foreach ($dummy_files as $d) {
                 $real_tk = Token::where('id', $d->real_store)->where('user_id', Auth::user()->id)->firstOrFail();
                 $realProObj = new Provider($real_tk->connection_name);
                 $temp = $realProObj->getFiles($d->path);
                 $data = array_merge($data, $temp);
             }
         }
         if (!empty($data)) {
             foreach ($data as $key => $row) {
                 $is_dir[$key] = $row['is_dir'];
                 $name[$key] = $row['name'];
             }
             array_multisort($is_dir, SORT_DESC, $name, SORT_ASC, $data);
         }
         $parent = $this->getNavbar($cname, $proObj->getPathName($any), $any);
         return view('pages.gtl.components.gtl-board', ['data' => $data, "cname" => $cname, 'parent' => $parent, 'in' => $id]);
     } else {
         return Redirect::to('/');
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $cliff = (new \DateTime())->modify('-5 minutes');
     \App\Token::where('created_at', '<', $cliff)->delete();
 }
 private function start($message)
 {
     $key = trim(str_replace('/start', '', $message['text']));
     $token = Token::findByToken($key);
     $app = App::findOrFail($token->app_id);
     $from = $message['from'];
     $telegramId = $from['id'];
     $telegramName = $from['first_name'];
     if (array_key_exists('last_name', $from)) {
         $telegramName .= ' ' . $from['last_name'];
     }
     if (array_key_exists('username', $from)) {
         $username = $from['username'];
     }
     try {
         $tg = TelegramUser::findByTelegramId($telegramId);
     } catch (ModelNotFoundException $e) {
         $tg = new TelegramUser();
         $tg->telegram_id = $telegramId;
     }
     $tg->name = $telegramName;
     $tg->save();
     if ($tg->status != '/start') {
         $tg->status = '/start';
         $tg->save();
         if (isset($username)) {
             $tg->username = $username;
         }
         try {
             $auth = Auth::findByAppAndTelegramUser($app, $tg);
         } catch (ModelNotFoundException $e) {
             $auth = new Auth();
             $auth->app_id = $app->id;
             $auth->telegram_user_id = $tg->id;
             $auth->email = generate_email() . '-' . $app->id . '-' . $tg->id . '@telegramlogin.com';
         }
         $auth->access_token = generate_access_token();
         $auth->active = true;
         $auth->save();
         $code = Code::create(array('app_id' => $app->id, 'auth_id' => $auth->id, 'code' => generate_code()));
         $url = $app->redirect_url . '?code=' . $code->code;
         if ($token->query_string) {
             $url .= '&' . $token->query_string;
         }
         $text = 'Please click this link to finish your signup at *' . $app->name . '*: ' . PHP_EOL;
         $text .= '[Click here](' . $url . ')';
         $params = array('text' => $text, 'chat_id' => $telegramId);
         $success = false;
         $trys = 0;
         while (!$success && $trys < 5) {
             $success = $this->send($params)['ok'];
             sleep(1);
             $trys++;
         }
         $token->delete();
         if ($app->client_id == 314159265) {
             $tg->status = str_replace('state=', '', $token->query_string);
         } else {
             $tg->status = 'access_granted';
         }
         $tg->save();
     }
 }
Exemple #30
0
 public function getToken($random)
 {
     $token = Token::all()->where('random', $random)->first();
     if ($token) {
         $token->user->profile_id = 3;
         $token->user->save();
         Mail::send('mail.to_new_madien', ['user' => $token->user], function ($message) use($token) {
             $message->to($token->user->email)->subject('Bienvenue chez MAD');
         });
         $name = $token->user->getFullName();
         return redirect('/')->with('message', 'Le compte de ' . $name . ' a été validé avec succès.');
     }
     return redirect('/');
 }