Last active
October 7, 2016 14:20
-
-
Save valex/0eadeaea275747fe74c9f07ff9adf41e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use repositories\UserRepository; | |
class UserController extends BaseController { | |
protected $imageUploader; | |
protected $userRepository; | |
public function __construct(\lib\Images\Uploader $imageUploader, UserRepository $userRepository) | |
{ | |
parent::__construct(); | |
$this->imageUploader = $imageUploader; | |
$this->userRepository = $userRepository; | |
} | |
public function uploadAvatar(User $user){ | |
if( ! Input::hasFile('file')){ | |
return \Response::json(trans('general.No files to upload'), 400); | |
} | |
$input = \Input::all(); | |
$rules = Image::$rules['upload']; | |
$rules['file'] = $rules['file'].'|max:'.\Config::get('file.max_upload_filesize'); | |
$validation = \Validator::make($input, $rules); | |
if ($validation->fails()) | |
{ | |
return \Response::json($validation->messages()->first(), 400); | |
} | |
try{ | |
$result = $this->imageUploader->upload(\Input::file('file'), $user); | |
} catch (\Exception $e){ | |
return \Response::json($e->getMessage(), 400); | |
} | |
$album = Album::where('user_id', $user->id)->where('name','=',Config::get('site.ava_album_name'))->first(); | |
if( ! $album){ | |
$album = new Album(); | |
$album->user_id = $user->id; | |
$album->name = \Config::get('site.ava_album_name'); | |
$album->save(); | |
} | |
$album->images()->attach($result->id); | |
$album->increment('num_images'); | |
\Event::fire('user.changeAvatar', [$user]); | |
return \Response::json('success', 200); | |
} | |
public function login() | |
{ | |
$input = array_map('trim',Input::all()); | |
$rules = User::$rules['login']; | |
$rules['username'] .= '|max:'.Setting::get('max_username_length'); | |
if(isset($input['recaptcha_required']) && $input['recaptcha_required'] == '1') | |
$rules['recaptcha_response_field'] = 'required|recaptcha'; | |
//$input['username']='_-!@\'"#$%^&*()[]{}|+.,?:;=~/\\'; | |
//$input['username']='Ник длинною в сорок символов вакепимронг'; | |
//$input['password']='ss'; | |
//$input['message_color']='00ff00'; | |
//$input['remember_me']='1'; | |
//$input['gender']='femalek'; | |
//$input['room']='3'; | |
// список запрещенных к регистрации ников | |
$validation = Validator::make($input, $rules); | |
$validation->setAttributeNames(array( | |
'username'=>trans('general.Your nickname'), | |
'password'=>trans('general.Password'), | |
//'message_color'=>trans('general.Message color'), | |
//'remember_me' => trans('general.Remember Me'), | |
'gender' => trans('general.Gender'), | |
'recaptcha_response_field' => trans('general.Captcha'), | |
)); | |
if($validation->passes()){ | |
//$remember = (isset($input['remember_me']) && $input['remember_me'])? true : false; | |
$remember = true; | |
// Retrieve the user by the attributes, or create it if it doesn't exist... | |
$user = User::where('username', $input['username'])->first(); | |
if(!$user) | |
{ | |
// если пользователь не существует - зарегистрировать нового пользователи и вход в чат | |
// проверить что ник не содержит матов | |
if(App::make('Obscene')->test($input['username'])) | |
{ | |
return Redirect::action('HomeController@index')->with('success', false)->withErrors(array('username'=>trans('general.Username contains obscene')))->withInput(); | |
} | |
$new_user = User::create(array( | |
'username'=>$input['username'], | |
'password'=>Hash::make($input['password']), | |
'gender'=>$input['gender'], | |
)); | |
switch($input['gender']){ | |
case 'female': | |
$message_color = \Setting::get('female_message_color'); | |
break; | |
default: | |
$message_color = \Setting::get('male_message_color'); | |
break; | |
} | |
$user_settings = array( | |
new UserSetting(array( | |
'key' => 'message_color', | |
'value' => $message_color | |
)), | |
); | |
foreach($user_settings as $user_setting) | |
{ | |
$new_user->settings()->save($user_setting); | |
} | |
Event::fire('user.new', array($new_user)); | |
} | |
// пользователь существует | |
if(Auth::attempt(array( | |
'username'=>$input['username'], | |
'password'=>$input['password'], | |
), $remember)) | |
{ | |
// пользователь существует и правильный пароль - вход | |
// изменить пол если требуется | |
$now_datetime = new DateTime('now', new DateTimeZone(Config::get('app.timezone'))); | |
$created_at = DateTime::createFromFormat('Y-m-d H:i:s', Auth::user()->created_at, new DateTimeZone(Config::get('app.timezone'))); | |
$diffInSeconds = $now_datetime->getTimestamp() - $created_at->getTimestamp(); | |
if($diffInSeconds <= Setting::get('gender_change_interval')){ | |
Auth::user()->gender = $input['gender']; | |
Auth::user()->save(); | |
} | |
// перенаправить на страницу | |
$action = UserSetting::get(Auth::user()->id,'redirect_when_enter_action'); | |
switch($action){ | |
case 'UserController@profile': | |
return Redirect::action($action, array('user' => Auth::user()->id)); | |
break; | |
default: | |
return Redirect::action('ChatController@index'); | |
break; | |
} | |
}else | |
{ | |
// пользователь существует и НЕправильный пароль - выберите другой ник (возможно перебор паролей) | |
return Redirect::action('HomeController@index')->with('success', false)->withErrors(array('username'=>trans('general.Username already exist')))->withInput(); | |
} | |
}else{ | |
return Redirect::action('HomeController@index')->with('success', false)->withErrors($validation)->withInput(); | |
} | |
/* | |
if($validation->passes()){ | |
$credentials = array( | |
array( | |
'username'=>$input['login_email'], | |
'password'=>$input['password'], | |
), | |
array( | |
'email'=>$input['login_email'], | |
'password'=>$input['password'], | |
), | |
); | |
$remember = isset($input['not_remember'])? false : true; | |
foreach($credentials as $credential){ | |
if(Auth::attempt($credential, $remember)){ | |
return Redirect::intended(); | |
break; | |
} | |
} | |
return Redirect::action('UserController@signin')->with('success', false)->withErrors(array('auth_failed'=>trans('user.Incorrect email or password')))->withInput(); | |
}else{ | |
return Redirect::action('UserController@signin')->with('success', false)->withErrors($validation)->withInput(); | |
} | |
*/ | |
} | |
public function loginWithFacebook() | |
{ | |
// https://github.com/artdarek/oauth-4-laravel | |
$signUpVia = 'facebook'; | |
if(Auth::check()) | |
{ | |
return Redirect::intended(); | |
} | |
// get data from input | |
$code = Input::get( 'code' ); | |
$fb = OAuth::consumer('Facebook', action('UserController@loginWithFacebook')); | |
// if code is provided get user data and sign in | |
if ( !empty( $code ) ) { | |
try{ | |
// This was a callback request from facebook, get the token | |
$token = $fb->requestAccessToken( $code ); | |
// Send a request with it | |
$result = json_decode( $fb->request( '/me' ), true ); | |
/* | |
array (size=11) | |
'id' => string '979633592061960' (length=15) | |
'email' => string '[email protected]' (length=18) | |
'first_name' => string 'Alex' (length=4) | |
'gender' => string 'male' (length=4) | |
'last_name' => string 'Versh' (length=5) | |
'link' => string 'https://www.facebook.com/app_scoped_user_id/979633592061960/' (length=60) | |
'locale' => string 'en_US' (length=5) | |
'name' => string 'Alex Versh' (length=10) | |
'timezone' => int 2 | |
'updated_time' => string '2014-03-21T10:21:35+0000' (length=24) | |
'verified' => boolean true | |
} | |
*/ | |
$user = User::where('signupvia', '=', $signUpVia) | |
->where('social_id', $result['id']) | |
->first(); | |
if( ! $user) | |
{ | |
$username = $result['first_name'].' '.$result['last_name']; | |
$gender = $result['gender'] == 'female' ? 'female' : 'male'; | |
$email = $result['email']; | |
$new_user = $this->userRepository->create([ | |
'username'=>$username, | |
'gender'=>$gender, | |
'signupvia'=>$signUpVia, | |
'social_id'=>$result['id'], | |
'email' => $email | |
]); | |
switch($gender){ | |
case 'female': | |
$message_color = \Setting::get('female_message_color'); | |
break; | |
default: | |
$message_color = \Setting::get('male_message_color'); | |
break; | |
} | |
$user_settings = array( | |
new UserSetting(array( | |
'key' => 'message_color', | |
'value' => $message_color | |
)), | |
); | |
foreach($user_settings as $user_setting) | |
{ | |
$new_user->settings()->save($user_setting); | |
} | |
$user = User::where('signupvia', '=', $signUpVia) | |
->where('social_id', $result['id']) | |
->first(); | |
Event::fire('user.new', array($new_user)); | |
} | |
Auth::login($user); | |
// success login | |
return Redirect::intended(); | |
}catch (Exception $ex){ | |
return Redirect::action('HomeController@index')->with('success', false)->withErrors(['auth_failed'=>$ex->getMessage()]); | |
} | |
} | |
// if not ask for permission first | |
else { | |
try{ | |
// get fb authorization | |
$url = $fb->getAuthorizationUri(); | |
// return to facebook login url | |
return Redirect::to((string)$url); | |
}catch (Exception $ex){ | |
return Redirect::action('HomeController@index')->with('success', false)->withErrors(['auth_failed'=>$ex->getMessage()]); | |
} | |
} | |
} | |
public function loginWithVk() | |
{ | |
// http://vk.com/dev | |
// https://vk.com/page-1_27445058 | |
$signUpVia = 'vk'; | |
if(Auth::check()) | |
{ | |
return Redirect::intended(); | |
} | |
// get data from input | |
$code = Input::get( 'code' ); | |
$vk = OAuth::consumer('Vkontakte', action('UserController@loginWithVk')); | |
// if code is provided get user data and sign in | |
if ( !empty( $code ) ) { | |
try{ | |
// This was a callback request from facebook, get the token | |
$token = $vk->requestAccessToken( $code ); | |
$extraparams = $token->getExtraParams(); | |
$uid = $extraparams['user_id']; | |
// Send a request with it | |
// http://vk.com/dev/api_requests | |
// http://vk.com/pages.php?o=-1&p=getProfiles | |
$result = json_decode( $vk->request( 'getProfiles?uid='.$uid.'&fields=uid,first_name,last_name,nickname,sex,bdate,city,country,photo_big' ), true ); | |
/* | |
array (size=1) | |
'response' => | |
array (size=1) | |
0 => | |
array (size=10) | |
'uid' => int 9475538 | |
'first_name' => string 'Александр' (length=18) | |
'last_name' => string 'Верш' (length=8) | |
'sex' => int 2 | |
'nickname' => string '' (length=0) | |
'bdate' => string '2.1.1920' (length=8) | |
'city' => int 628 | |
'country' => int 2 | |
'photo_big' => string 'http://cs621324.vk.me/v621324538/24fd/jj-LexN_Kyw.jpg' (length=53) | |
*/ | |
$user = User::where('signupvia', '=', $signUpVia) | |
->where('social_id', $result['response'][0]['uid']) | |
->first(); | |
if( ! $user) | |
{ | |
$username = $result['response'][0]['first_name'].' '.$result['response'][0]['last_name']; | |
$gender = $result['response'][0]['sex'] == '1' ? 'female' : 'male'; | |
$new_user = User::create(array( | |
'username'=>$username, | |
'gender'=>$gender, | |
'signupvia'=>$signUpVia, | |
'social_id'=>$result['response'][0]['uid'], | |
)); | |
switch($gender){ | |
case 'female': | |
$message_color = \Setting::get('female_message_color'); | |
break; | |
default: | |
$message_color = \Setting::get('male_message_color'); | |
break; | |
} | |
$user_settings = array( | |
new UserSetting(array( | |
'key' => 'message_color', | |
'value' => $message_color | |
)), | |
); | |
foreach($user_settings as $user_setting) | |
{ | |
$new_user->settings()->save($user_setting); | |
} | |
$user = User::where('signupvia', '=', $signUpVia) | |
->where('social_id', $result['response'][0]['uid']) | |
->first(); | |
Event::fire('user.new', array($new_user)); | |
} | |
Auth::login($user); | |
// success login | |
return Redirect::intended(); | |
}catch (Exception $ex){ | |
return Redirect::action('HomeController@index')->with('success', false)->withErrors(['auth_failed'=>$ex->getMessage()]); | |
} | |
}else{ | |
try{ | |
// get vk authorization | |
$url = $vk->getAuthorizationUri(); | |
// return to vkontakte login url | |
return Redirect::to((string)$url); | |
}catch (Exception $ex){ | |
return Redirect::action('HomeController@index')->with('success', false)->withErrors(['auth_failed'=>$ex->getMessage()]); | |
} | |
} | |
} | |
public function logout() | |
{ | |
// delete logged cookie | |
if (isset($_COOKIE['logged'])) { | |
unset($_COOKIE['logged']); | |
setcookie('logged', null, -1, '/'); | |
} | |
$redirect = Redirect::action('HomeController@index'); | |
if(!Auth::guest()) | |
{ | |
// если установлен флаг и кука еще не существует | |
if(Auth::user()->set_ban_cookie == 1 && Cookie::get('ban') != 1) | |
{ | |
$cookie = Cookie::make('ban', '1', round(Setting::get('ban_cookie_duration') / 60)); | |
$redirect = $redirect->withCookie($cookie); | |
} | |
Auth::user()->setBanCookieFlag(false); | |
if(Auth::user()->isUserDenied()) | |
{ | |
$redirect = $redirect->withErrors(['auth_failed'=>trans('general.You are denied access to the chat')]); | |
} | |
} | |
Auth::logout(); | |
// Removing All Items From The Session | |
// Session::flush(); | |
return $redirect; | |
} | |
public function profile(User $user) | |
{ | |
$seo_anchors = array( | |
'в чате', | |
'в видео чате', | |
'в запорожском видео чате', | |
'в запорожском чате', | |
'в видео чате Запорожья', | |
'в чате Запорожья', | |
); | |
$mod = $user->id%10; | |
switch($mod){ | |
case 0: | |
$seo_anchor = $seo_anchors[0]; | |
break; | |
case 1: | |
$seo_anchor = $seo_anchors[1]; | |
break; | |
case 2: | |
$seo_anchor = $seo_anchors[2]; | |
break; | |
case 3: | |
$seo_anchor = $seo_anchors[3]; | |
break; | |
case 4: | |
$seo_anchor = $seo_anchors[4]; | |
break; | |
case 5: | |
$seo_anchor = $seo_anchors[5]; | |
break; | |
case 6: | |
$seo_anchor = $seo_anchors[2]; | |
break; | |
case 7: | |
$seo_anchor = $seo_anchors[3]; | |
break; | |
case 8: | |
$seo_anchor = $seo_anchors[4]; | |
break; | |
case 9: | |
$seo_anchor = $seo_anchors[5]; | |
break; | |
} | |
$seo_suffix = '<span itemscope itemtype="http://schema.org/Brand"><a href="'.action('HomeController@index').'" itemprop="url"><span itemprop="name">'.$seo_anchor.'</span></a></span>'; | |
$albums = $user->albums()->orderBy('id','desc'); | |
$total_albums = $albums->count(); | |
$last_albums = $albums->where('name', '<>', Config::get('site.ava_album_name'))->take(2)->get(); | |
//$last_not_protected_albums = array(); | |
//foreach($last_albums as $last_album){ | |
// if($last_album->is) | |
//} | |
$last_albums_views = []; | |
$thumbWidth = 300; | |
$thumbHeight = 240; | |
foreach($last_albums as $last_album){ | |
$coverImageUrl = $last_album->getCoverImageUrl(\App::make('lib\Images\FixedWidthAndHeightThumb', [$thumbWidth, $thumbHeight])); | |
$last_albums_views[] = \View::make('album.partials.item', array( | |
'bootstrap_col' => 12, | |
'album' => $last_album, | |
'user' => $user, | |
'coverImageUrl' => $coverImageUrl, | |
)); | |
} | |
$modelVideos = $user->videoModels(); | |
$total_videos = $modelVideos->count(); | |
$last_modelVideos = $modelVideos->orderBy('id', 'desc')->take(2)->get(); | |
$videoHostingFactory = new \lib\VideoHostings\VideoHostingFactory(); | |
$last_videos_views = array(); | |
foreach($last_modelVideos as $last_modelVideo){ | |
$videoHosting = $videoHostingFactory->create($last_modelVideo->video->getUrl()); | |
$last_videos_views[] = View::make('video.partials.item', array( | |
'bootstrap_col' => 12, | |
'modelVideo' => $last_modelVideo, | |
'videoHosting' => $videoHosting, | |
)); | |
} | |
$otherData = array(); | |
$otherData['wallView'] = $user->getWallView(); | |
$place = $user->place()->first(); | |
$data=array( | |
'title' => $user->getNickname(), | |
'header'=>link_to_action('UserController@profile', $user->getNickname(), array('user'=>$user->id)), | |
'user'=>$user, | |
'ava'=>$user->lastAvaImage(), | |
'avaUrl'=>$user->lastAvaImageUrl(\App::make('lib\Images\FixedWidthThumb', [300])), | |
'total_albums'=>$total_albums, | |
'last_albums_views'=>$last_albums_views, | |
'total_videos'=>$total_videos, | |
'last_videos_views'=>$last_videos_views, | |
'place'=>$place, | |
'seo_suffix' => $seo_suffix, | |
); | |
$data = array_merge($data, $otherData); | |
return View::make("user.profile", $data); | |
} | |
public function editProfile(User $user){ | |
Auth::user()->checkRights($user->id); | |
if (Request::isMethod('post')) | |
{ | |
SiteHelper::global_xss_clean(); | |
$input_all = Input::all(); | |
$validation = Validator::make($input_all, User::$rules['editProfile']); | |
$validation->setAttributeNames(array( | |
'birthday_day'=>trans('general.Day'), | |
'birthday_month'=>trans('general.Month'), | |
'birthday_year'=>trans('general.Year'), | |
'firstname'=>trans('general.Firstname'), | |
'lastname'=>trans('general.Lastname'), | |
'family_tag_id'=>trans('general.Family status'), | |
'child_tag_id'=>trans('general.Child'), | |
'growth'=>trans('general.Growth'), | |
'weight'=>trans('general.Weight'), | |
'about_yourself'=>trans('general.About yourself'), | |
)); | |
$validation->sometimes(array('birthday_day', 'birthday_month', 'birthday_year'), 'date', function($input) | |
{ | |
if(!$input->birthday_month || | |
!$input->birthday_day || | |
!$input->birthday_year){ | |
return false; | |
} | |
return !checkdate($input->birthday_month, $input->birthday_day, $input->birthday_year); | |
}); | |
if($validation->passes()){ | |
$user->firstname = $input_all['firstname']; | |
$user->lastname = $input_all['lastname']; | |
$user->birthday = "{$input_all['birthday_year']}-{$input_all['birthday_month']}-{$input_all['birthday_day']}"; | |
$user->growth = ($input_all['growth']) ? intval($input_all['growth']) : NULL; | |
$user->weight = ($input_all['weight']) ? intval($input_all['weight']) : NULL; | |
$user->family_tag_id = ($input_all['family_tag_id']) ? intval($input_all['family_tag_id']) : NULL; | |
$user->child_tag_id = ($input_all['child_tag_id']) ? intval($input_all['child_tag_id']) : NULL; | |
$user->about_yourself = StrHelper::getBrokenText($input_all['about_yourself'], Setting::get('max_length_unbroken_line')); | |
$user->save(); | |
return Redirect::action('UserController@profile', array($user->id)); | |
}else{ | |
return Redirect::action('UserController@editProfile', array($user->id))->with('success', false)->withErrors($validation)->withInput(); | |
} | |
} | |
$place = $user->place()->first(); | |
$lat = $place ? $place->lat : Setting::get('default_lat'); | |
$lng = $place ? $place->lng : Setting::get('default_lng'); | |
$data=array( | |
'title' => $user->getNickname().' - '.trans('general.Editing profile'), | |
'header'=>$user->getNickname().' - '.trans('general.Editing profile'), | |
'breadcrumbs' => array( | |
array( | |
'url' => action('UserController@profile', array('user'=>$user->id)), | |
'title' => $user->getNickname(), | |
), | |
array( | |
'title' => trans('general.Editing profile'), | |
), | |
), | |
'user'=>$user, | |
'place'=>$place, | |
'editProfilePlaceInfo'=>View::make('place.editProfilePlaceInfo', array('place'=>$place)), | |
'lat'=>$lat, | |
'lng'=>$lng, | |
); | |
return View::make("user.editProfile", $data); | |
} | |
public function settings() | |
{ | |
$user = Auth::user(); | |
if (Request::isMethod('post')) | |
{ | |
SiteHelper::global_xss_clean(); | |
$input_all = Input::all(); | |
$validation = Validator::make($input_all, User::$rules['editSettings']); | |
$validation->setAttributeNames(array( | |
'redirect_when_enter_action'=>trans('general.When enter open'), | |
'private_height'=>trans('general.Private height'), | |
)); | |
if($validation->passes()){ | |
foreach($input_all as $setting_key=>$setting_value) | |
{ | |
if(Setting::get($setting_key) === NULL) | |
continue; | |
$userSetting = UserSetting::firstOrNew(array( | |
'user_id'=>Auth::user()->id, | |
'key'=> $setting_key, | |
)); | |
$userSetting->value = $setting_value; | |
$userSetting->save(); | |
} | |
return Redirect::action('UserController@settings')->with('msg', trans('general.Refresh the page chat to change stepped into force')); | |
}else{ | |
return Redirect::action('UserController@settings')->with('success', false)->withErrors($validation)->withInput(); | |
} | |
} | |
$data=array( | |
'title' => $user->getNickname().' - '.trans('general.My Settings'), | |
'header'=>'<a href="'.action('UserController@settings').'">'.trans('general.Settings').'</a>', | |
'breadcrumbs' => array( | |
array( | |
'url' => action('UserController@profile', array('user'=>$user->id)), | |
'title' => $user->getNickname(), | |
), | |
array( | |
'url' => action('UserController@settings'), | |
'title' => trans('general.Settings'), | |
), | |
), | |
'user'=>$user, | |
); | |
return View::make("user.settings", $data); | |
} | |
public function signup() | |
{ | |
if(Auth::check()) | |
{ | |
return Redirect::intended(); | |
} | |
$data=array( | |
'title'=>trans('general.Registration'), | |
//'meta_description'=>'meta descr', | |
//'meta_keywords'=>'meta_keywrds', | |
); | |
return View::make('user.signup', $data); | |
} | |
public function store() | |
{ | |
$input_all = array_map('trim', Input::all()); | |
$signup_rules = User::$rules['signup']; | |
//if(Cookie::get('correct_recaptcha_response_field') == 'true'){ | |
// unset($signup_rules['recaptcha_response_field']); | |
//} | |
$validation = Validator::make($input_all, $signup_rules); | |
$validation->setAttributeNames(array( | |
'username'=>trans('general.Nickname'), | |
'email'=>trans('general.Email'), | |
'password'=>trans('general.Password'), | |
'password_confirmation'=>trans('general.Confirm Password'), | |
'agree'=>trans('general.User agreement'), | |
'recaptcha_response_field'=>trans('general.Verification code'), | |
)); | |
if($validation->passes()){ | |
$user = new User($input_all); | |
$user->password = Hash::make($input_all['password']); | |
$user->signupvia = 'mail'; | |
$user->save(); | |
return Redirect::action('UserController@signup')->with('success', true); | |
}else{ | |
$redirect = Redirect::action('UserController@signup')->with('success', false)->withErrors($validation)->withInput(); | |
//if(!($validation->errors()->has('recaptcha_response_field'))){ | |
// $redirect->withCookie(Cookie::make('correct_recaptcha_response_field', 'true')); | |
//} | |
return $redirect; | |
} | |
} | |
public function signinWithTwitter() | |
{ | |
// https://github.com/artdarek/oauth-4-laravel | |
// https://github.com/Lusitanian/PHPoAuthLib/tree/master/examples | |
if(Auth::check()) | |
{ | |
return Redirect::intended(); | |
} | |
// get data from input | |
$oauth_token = Input::get( 'oauth_token' ); | |
$oauth_verifier = Input::get( 'oauth_verifier' ); | |
$denied = Input::get( 'denied' ); | |
$twitterService = OAuth::consumer('Twitter', action('UserController@signinWithTwitter')); | |
if ( !empty( $oauth_token ) && !empty( $oauth_verifier ) ) { | |
try{ | |
$token = $twitterService->getStorage()->retrieveAccessToken('Twitter'); | |
// This was a callback request from twitter, get the token | |
$twitterService->requestAccessToken( | |
$oauth_token, | |
$oauth_verifier, | |
$token->getRequestTokenSecret() | |
); | |
// Send a request now that we have access token | |
$result = json_decode($twitterService->request('account/verify_credentials.json')); | |
/* | |
* object(stdClass)#203 (39) { | |
["id"]=> | |
int(84559887) | |
["id_str"]=> | |
string(8) "84559887" | |
["name"]=> | |
string(10) "Alex Versh" | |
["screen_name"]=> | |
string(9) "valex_ukr" | |
["location"]=> | |
string(7) "Ukraine" | |
["description"]=> | |
string(0) "" | |
["url"]=> | |
string(22) "http://t.co/gDKwhi8ibO" | |
["entities"]=> | |
object(stdClass)#202 (2) { | |
["url"]=> | |
object(stdClass)#204 (1) { | |
["urls"]=> | |
array(1) { | |
[0]=> | |
object(stdClass)#205 (4) { | |
["url"]=> | |
string(22) "http://t.co/gDKwhi8ibO" | |
["expanded_url"]=> | |
string(19) "http://valex.net.ru" | |
["display_url"]=> | |
string(12) "valex.net.ru" | |
["indices"]=> | |
array(2) { | |
[0]=> | |
int(0) | |
[1]=> | |
int(22) | |
} | |
} | |
} | |
} | |
["description"]=> | |
object(stdClass)#206 (1) { | |
["urls"]=> | |
array(0) { | |
} | |
} | |
} | |
["protected"]=> | |
bool(false) | |
["followers_count"]=> | |
int(2) | |
["friends_count"]=> | |
int(10) | |
["listed_count"]=> | |
int(0) | |
["created_at"]=> | |
string(30) "Fri Oct 23 10:55:47 +0000 2009" | |
["favourites_count"]=> | |
int(0) | |
["utc_offset"]=> | |
int(-10800) | |
["time_zone"]=> | |
string(9) "Greenland" | |
["geo_enabled"]=> | |
bool(false) | |
["verified"]=> | |
bool(false) | |
["statuses_count"]=> | |
int(0) | |
["lang"]=> | |
string(2) "en" | |
["contributors_enabled"]=> | |
bool(false) | |
["is_translator"]=> | |
bool(false) | |
["is_translation_enabled"]=> | |
bool(false) | |
["profile_background_color"]=> | |
string(6) "C0DEED" | |
["profile_background_image_url"]=> | |
string(48) "http://abs.twimg.com/images/themes/theme1/bg.png" | |
["profile_background_image_url_https"]=> | |
string(49) "https://abs.twimg.com/images/themes/theme1/bg.png" | |
["profile_background_tile"]=> | |
bool(false) | |
["profile_image_url"]=> | |
string(68) "http://pbs.twimg.com/profile_images/494327278/4e_120width_normal.jpg" | |
["profile_image_url_https"]=> | |
string(69) "https://pbs.twimg.com/profile_images/494327278/4e_120width_normal.jpg" | |
["profile_link_color"]=> | |
string(6) "0084B4" | |
["profile_sidebar_border_color"]=> | |
string(6) "C0DEED" | |
["profile_sidebar_fill_color"]=> | |
string(6) "DDEEF6" | |
["profile_text_color"]=> | |
string(6) "333333" | |
["profile_use_background_image"]=> | |
bool(true) | |
["default_profile"]=> | |
bool(true) | |
["default_profile_image"]=> | |
bool(false) | |
["following"]=> | |
bool(false) | |
["follow_request_sent"]=> | |
bool(false) | |
["notifications"]=> | |
bool(false) | |
} | |
*/ | |
if($result && isset($result->screen_name)){ | |
/* | |
* @todo абаЕаДаОбаВбаАбаИбб баЕаГаИбббаАбаИб б аОаДаИаНаАаКаОаВбаМаИ username аНаО баАаЗаНбаМаИ signupvia | |
* аНаАаПбаИаМаЕб alex аИаЗ facebook аИ alex аИаЗ google | |
*/ | |
$user = User::where('username', '=', $result->screen_name)->first(); | |
if(!$user){ | |
$user = new User(); | |
$user->signupvia = 'twitter'; | |
$user->username = $result->screen_name; | |
$user->save(); | |
}elseif($user->signupvia != 'twitter') { | |
throw new Exception(sprintf(trans('user.username with already exist'), $result->screen_name)); | |
} | |
Auth::login($user); | |
// success login | |
return Redirect::intended(); | |
}else{ | |
throw new Exception(trans('user.Malformed response from the twitter api')); | |
} | |
// echo 'result: <pre>' . print_r($result, true) . '</pre>'; | |
}catch (Exception $ex){ | |
return Redirect::action('UserController@signin')->with('success', false)->withErrors(['auth_failed'=>$ex->getMessage()]); | |
} | |
}elseif(!empty($denied)){ | |
// click cancel on twitter authorization form | |
return Redirect::action('UserController@signin'); | |
} | |
// if not ask for permission first | |
else { | |
try{ | |
// extra request needed for oauth1 to request a request token :-) | |
$token = $twitterService->requestRequestToken(); | |
$url = $twitterService->getAuthorizationUri(['oauth_token' => $token->getRequestToken()]); | |
// return redirect to twitter login url | |
return Redirect::to((string)$url); | |
}catch (Exception $ex){ | |
return Redirect::action('UserController@signin')->with('success', false)->withErrors(['auth_failed'=>$ex->getMessage()]); | |
} | |
} | |
} | |
public function signinWithGoogle() | |
{ | |
if(Auth::check()) | |
{ | |
return Redirect::intended(); | |
} | |
// get data from input | |
$code = Input::get( 'code' ); | |
// get google service | |
$googleService = OAuth::consumer( 'Google', 'http://booknet.example.com/user/signinWithGoogle'/*, action('UserController@signinWithGoogle' )*/); | |
// if code is provided get user data and sign in | |
if ( !empty( $code ) ) { | |
try{ | |
// This was a callback request from google, get the token | |
$token = $googleService->requestAccessToken( $code ); | |
// Send a request with it | |
$result = json_decode( $googleService->request( 'https://www.googleapis.com/oauth2/v1/userinfo' ), true ); | |
/* | |
array(10) { | |
["id"]=> | |
string(21) "112217610791703529861" | |
["email"]=> | |
string(15) "[email protected]" | |
["verified_email"]=> | |
bool(true) | |
["name"]=> | |
string(10) "Alex Versh" | |
["given_name"]=> | |
string(4) "Alex" | |
["family_name"]=> | |
string(5) "Versh" | |
["link"]=> | |
string(45) "https://plus.google.com/112217610791703529861" | |
["picture"]=> | |
string(92) "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg" | |
["gender"]=> | |
string(4) "male" | |
["locale"]=> | |
string(5) "en-GB" | |
} | |
*/ | |
if($result && isset($result['id'])){ | |
/* | |
* @todo абаЕаДаОбаВбаАбаИбб баЕаГаИбббаАбаИб б аОаДаИаНаАаКаОаВбаМаИ username аНаО баАаЗаНбаМаИ signupvia | |
* аНаАаПбаИаМаЕб alex аИаЗ facebook аИ alex аИаЗ google | |
*/ | |
$user = User::where('username', '=', $result['id'])->first(); | |
if(!$user){ | |
$user = new User(); | |
$user->signupvia = 'google'; | |
if(isset($result['given_name'])) | |
$user->firstname = $result['given_name']; | |
if(isset($result['family_name'])) | |
$user->lastname = $result['family_name']; | |
if(isset($result['email'])) | |
$user->email = $result['email']; | |
$user->username = $result['id']; | |
$user->save(); | |
}elseif($user->signupvia != 'google') { | |
throw new Exception(sprintf(trans('user.username with already exist'), $result['id'])); | |
} | |
Auth::login($user); | |
// success login | |
return Redirect::intended(); | |
} | |
}catch (Exception $ex){ | |
return Redirect::action('UserController@signin')->with('success', false)->withErrors(array('auth_failed'=>$ex->getMessage())); | |
} | |
}else{ | |
try{ | |
// get google authorization | |
$url = $googleService->getAuthorizationUri(); | |
// return to vkontakte login url | |
return Redirect::to((string)$url); | |
}catch (Exception $ex){ | |
return Redirect::action('UserController@signin')->with('success', false)->withErrors(array('auth_failed'=>$ex->getMessage())); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment