I see the documentation https://www.twilio.com/docs/video/api/rooms-resource#rooms-list-resource
But i cannot find how to set the mediaRegion.
Can you tell me how please?
This is what i try but it not works :
use Symfony\Component\HttpFoundation\Request;
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\VideoGrant;
use Twilio\Rest\Client;
class VideoconferencingController extends Controller
{
public function createAction(Request $request, $roomName)
{
$user = $this->getUser();
// An identifier for your app - can be anything you'd like
$identity = $user->getFullName();
// Create access token, which we will serialize and send to the client
$token = new AccessToken(
$twilioAccountSid,
$twilioApiKey,
$twilioApiSecret,
3600,
$identity
);
// Create Video grant
$videoGrant = new VideoGrant();
$videoGrant->setRoom($roomName);
// Add grant to token
$token->addGrant($videoGrant);
$twilio = new Client($twilioApiKey, $twilioApiSecret, $twilioAccountSid);
$room = $twilio
->video
->v1
// ->rooms($roomName)
->rooms('RM2900c0f08a237f6e978fc413cb997403')
->mediaRegion('ie1')
->update('completed')
;
error_log(print_r($room,1));
// render token to string
return [
'token' => $token->toJWT(),
'roomName' => $roomName,
];
}
Best regards,
Bruno
I found what i need to do.
Create the room with mediaRegion :
use Symfony\Component\HttpFoundation\Request;
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\VideoGrant;
use Twilio\Rest\Client;
class VideoconferencingController extends Controller
{
public function createAction(Request $request, $twilioRoomSid, $staffId, $roomName)
{
$twilioRoomSid = ('undefined' == $twilioRoomSid) ? null : $twilioRoomSid;
$user = $this->getUser();
$twilioAccountSid = $this->getParameter('twilio_account_sid');
$twilioApiKey = $this->getParameter('twilio_api_key');
$twilioApiSecret = $this->getParameter('twilio_api_secret');
$now = new \DateTime();
// Get or create room
$twilio = new Client($twilioApiKey, $twilioApiSecret, $twilioAccountSid);
if ($twilioRoomSid) {
$room = $twilio
->video
->v1
->rooms($twilioRoomSid)
->fetch()
;
}
$createRoom = (!$twilioRoomSid || 'completed' == $room->status) ? true : false;
if ($createRoom) {
$room = $twilio
->video
->v1
->rooms
->create([
'mediaRegion' => 'ie1',
'uniqueName' => $roomName
]
)
;
$twilioRoomSid = $room->sid;
$staff = $this->findOr404('App:Staff', $staffId);
$staff->setTwilioRoomSid($twilioRoomSid);
$this->flush();
}
// Authorize room
$identity = $user->getFullName();
// Create access token, which we will serialize and send to the client
$token = new AccessToken(
$twilioAccountSid,
$twilioApiKey,
$twilioApiSecret,
3600,
$identity
);
// Create Video grant
$videoGrant = new VideoGrant();
$videoGrant->setRoom($twilioRoomSid);
// Add grant to token
$token->addGrant($videoGrant);
// render token to string
return [
'token' => $token->toJWT(),
'roomName' => $roomName,
];
}
}
Related
So I just want to add login with google feature on my working authentication web app (with Codeigniter Shield package). I've already create a login_google function on Login controller that extends LoginController from shield package like this :
LoginController
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\Shield\Controllers\LoginController;
class Login extends LoginController
{
function __construct()
{
require_once __DIR__ . '/../../vendor/autoload.php';
$this->userModel = new \App\Models\UserModel();
$this->google_client = new \Google_Client();
$this->google_client->setClientId(getenv('OAuth2.clientID'));
$this->google_client->setClientSecret(getenv('OAuth2.clientSecret'));
$this->google_client->setRedirectUri('http://localhost:8080/login_google');
$this->google_client->addScope('email');
$this->google_client->addScope('profile');
}
public function loginView()
{
if (auth()->loggedIn()) {
return redirect()->to(config('Auth')->loginRedirect());
}
/** #var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
// If an action has been defined, start it up.
if ($authenticator->hasAction()) {
return redirect()->route('auth-action-show');
}
$data['google_button'] = "<a href='".$this->google_client->createAuthUrl()."'><img src='https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png' /></a>";
return view('login', $data);
}
public function loginAction(): RedirectResponse
{
// Validate here first, since some things,
// like the password, can only be validated properly here.
$rules = $this->getValidationRules();
if (! $this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$credentials = $this->request->getPost(setting('Auth.validFields'));
$credentials = array_filter($credentials);
$credentials['password'] = $this->request->getPost('password');
$remember = (bool) $this->request->getPost('remember');
/** #var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
// Attempt to login
$result = $authenticator->remember($remember)->attempt($credentials);
if (! $result->isOK()) {
return redirect()->route('login')->withInput()->with('error', $result->reason());
}
/** #var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
// If an action has been defined for login, start it up.
if ($authenticator->hasAction()) {
return redirect()->route('auth-action-show')->withCookies();
}
return redirect()->to(config('Auth')->loginRedirect())->withCookies();
}
public function login_google() {
$token = $this->google_client->fetchAccessTokenWithAuthCode($this->request->getVar('code'));
if (!isset($token['error'])) {
$this->google_client->setAccessToken($token['access_token']);
$this->session->set('access_token', $token['access_token']);
$google_service = new \Google\Service\Oauth2($this->google_client);
$data = $google_service->userinfo->get();
$userdata = array();
if ($this->userModel->isAlreadyRegister($data['id'])) {
$userdata = [
'first_name' => $data['givenName'],
'last_name' => $data['familyName'],
'email' => $data['email'],
'avatar' => $data['picture'],
];
$this->userModel->updateUserData($userdata, $data['id']);
} else {
$userdata = [
'first_name' => $data['givenName'],
'last_name' => $data['familyName'],
'email' => $data['email'],
'avatar' => $data['picture'],
'oauth_id' => $data['id'],
];
$this->userModel->insertUserData($userdata);
}
$this->session->set('LoggedUserData', $userdata);
} else {
$this->session->set("error", $token['error']);
return redirect('/register');
}
return redirect()->to('/profile');
}
}
UserModel like this :
UserMode
<?php
namespace App\Models;
use CodeIgniter\Model;
use CodeIgniter\Shield\Models\UserModel as ModelsUserModel;
class UserModel extends ModelsUserModel
{
protected $allowedFields = [
'username',
'status',
'status_message',
'active',
'last_active',
'deleted_at',
'gender',
'first_name',
'last_name',
'avatar',
'phone_number',
'full_address',
'oauth_id',
];
function isAlreadyRegister($authid){
return $this->db->table('users')->getWhere(['id'=>$authid])->getRowArray()>0?true:false;
}
function updateUserData($userdata, $authid){
$this->db->table("users")->where(['id'=>$authid])->update($userdata);
}
function insertUserData($userdata){
$this->db->table("users")->insert($userdata);
}
}
But everytime I clicked sign in with google button, it won't work (the interface for choosing google account to authenticate is worked) and always return to login page
am I missing something when combining CodeIgniter Shield with Google Oauth ? Anyone can help ? TIA
A new package has been created for OAuth with Shield package: https://github.com/datamweb/shield-oauth
You can use it instead of your own one.
I am creating a multi vendor web application in which I need to implement login with Facebook for customers. vendor can have their own domain or sub-domain and also own customers. In the website, I have implemented Facebook login by using env variables. the code is below.
Routes for facebook login
Route::get('auth/facebook', 'FacebookController#redirectToFacebook');
Route::get('auth/facebook/callback', 'FacebookController#handleFacebookCallback');
In config/services.php
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => env('FACEBOOK_CALLBACK_URL'),
],
Facebook Controller function
public function redirectToFacebook()
{
return Socialite::driver('facebook')->redirect();
}
public function handleFacebookCallback()
{
try {
$user = Socialite::driver('facebook')->user();
$user_name = $user->getName();
$user_email = $user->getEmail();
$facebook_auth_id = $user->getId();
/* other code */
} catch (Exception $e) {
return redirect()->route('login')->with(['error' => "facebook login failed."]);
}
}
but I want to use vendor's Facebook key and secret which stored in database. How can I use dynamic variables here to implement the functionality?
Make sure these packages should be included in your Controller
use Laravel\Socialite\SocialiteManager;
use Socialite;
use Laravel\Socialite\Two\FacebookProvider;
Use below code in your controller
public function redirectToFacebook(Request $request)
{
$fb = $this->configDriver($request);
return $fb->redirect();
}
private function configDriver(Request $request, $domain = '', $driver = 'facebook')
{
$config['client_id'] = 'your_client_id';
$config['client_secret'] = 'your_client_secret';
$config['redirect'] = 'your_redirect_url';
return Socialite::buildProvider(FacebookProvider::class, $config);
}
public function handleSocialCallback(Request $request, $domain = '', $driver = 'facebook')
{
$usr = $this->configDriver($request)->stateless()->user();
$name = $user->getName();
$email = $user->getEmail();
$facebook_id = $user->getId();
/*save data in db*/
}
This has been implemented using Laravel Socialite.
https://github.com/jd-patel/laravel-social-login
I'm using yii2-dektrium to allow users login with their facebook's accounts.
After the login is done, I need to make API request from my server to get data of the user's accounts. One example of request is:
$client = Yii::$app->authClientCollection->getClient('facebook');
$response = $client->createApiRequest()
->setMethod('GET')
->setUrl('v2.12/me/accounts')
->send();
The access_token is saved on session so I need to persist it to the database.
I already added a column access_token to the social_account default table of yii2-dektrium but I don't know how to get and save it, and further more, how to apply it to the requests.
After reading for a while. I think the way to save it is overriding the method connect in dektrium\user\controllers\SecurityController.
public function connect(ClientInterface $client)
{
/** #var Account $account */
$account = \Yii::createObject(Account::className());
$event = $this->getAuthEvent($account, $client);
$this->trigger(self::EVENT_BEFORE_CONNECT, $event);
$account->connectWithUser($client);
$this->trigger(self::EVENT_AFTER_CONNECT, $event);
$this->action->successUrl = Url::to(['/user/settings/networks']);
}
And for applying to the request, override applyAccessTokenToRequest on yii\authclient\clients\Facebook
public function applyAccessTokenToRequest($request, $accessToken)
{
parent::applyAccessTokenToRequest($request, $accessToken);
$data = $request->getData();
if (($machineId = $accessToken->getParam('machine_id')) !== null) {
$data['machine_id'] = $machineId;
}
$data['appsecret_proof'] = hash_hmac('sha256', $accessToken->getToken(), $this->clientSecret);
$request->setData($data);
}
I can't get it done. And I'm not sure if it is the right way to do it. What I'm missing?
For save the access_token the first time you have to overwrite the connect action from \dektrium\user\controllers\SecurityController.
class SecurityController extends \dektrium\user\controllers\SecurityController
{
public function connect(ClientInterface $client)
{
// default implementation of connect
$account = \Yii::createObject(Account::className());
$event = $this->getAuthEvent($account, $client);
$this->trigger(self::EVENT_BEFORE_CONNECT, $event);
$account->connectWithUser($client);
$this->trigger(self::EVENT_AFTER_CONNECT, $event);
// get acess_token from $client
$access_token['tokenParamKey'] = $client->getAccessToken()->tokenParamKey;
$access_token['tokenSecretParamKey'] = $client->getAccessToken()->tokenSecretParamKey;
$access_token['createTimestamp'] = $client->getAccessToken()->createTimestamp;
$access_token['_expireDurationParamKey'] = $client->getAccessToken()->getExpireDurationParamKey();
$access_token['_params'] = $client->getAccessToken()->getParams();
// save acess_token to social_account table
$model = SocialAccount::find()->where(['provider' => $client->getName()])->andWhere(['user_id' => Yii::$app->user->id])->one();
$model->access_token = \yii\helpers\Json::encode($access_token);
$model->save(false);
$this->action->successUrl = Url::to(['/user/settings/networks']);
}
}
To get the access_token store in the database for further API Requests create a class that extends yii\authclient\SessionStateStorage and overwrite get method.
namespace app\models\authclient;
class DbStateStorage extends SessionStateStorage
{
public function get($key)
{
// $key is a complex string that ends with 'token' if the value to get is the actual access_token
$part = explode('_', $key);
if (count($part) == 3 && $part[2] == 'token') {
$account = SocialAccount::find()
->where(['provider' => $part[1]])
->andWhere(['user_id' => Yii::$app->user->id])
->one();
if ($account != null) {
$access_token = json_decode($account->access_token);
$token = new \yii\authclient\OAuthToken();
$token->createTimestamp = $access_token->createTimestamp;
$token->tokenParamKey = $access_token->tokenParamKey;
$token->tokenSecretParamKey = $access_token->tokenSecretParamKey;
$token->setParams((array)$access_token->_params);
$token->setExpireDurationParamKey($access_token->_expireDurationParamKey);
return $token;
}
}
if ($this->session !== null) {
return $this->session->get($key);
}
return null;
}
}
Finally set the DbStateStorage to your authclient
class Facebook extends \dektrium\user\clients\Facebook
{
public function __construct()
{
$this->setStateStorage('app\models\authclient\DbStateStorage');
}
}
im working with magento api, and i need verify my connect.
how to call method APIauthentication with $client object? because im getting error on this: Error: Function ("APIauthentication") is not a valid method for this service
thanks for the help.
this is my class:
<?php
class Magento {
const PRODUCTS_LIST = 'catalog_product.list';
public function Verify( $data )
{
$client = new SoapClient( $data['store_url'] );
$verify = $client->APIauthentication( $data['api_user'], $data['api_key'] );
if ($verify)
{
return $this->Register( $data['store_url'], $data['api_user'], $data['api_key'] );
}
}
public function APIauthentication( $apiUser, $apiKey ) {
$client = $this->_getClient();
$token = $client->login( $apiUser, $apiKey );
$this->_setToken( $token );
return $this->_apiJsonResult( $token );
}
}
there is url:
$data['store_url'] = 'http://localhost:8888/magento/api/soap/?wsdl';
firstly i need verify, second - get list:
// For products
public function getProducts()
{
return $client->APIgetProductsList();
}
/*
* Get product list
*/
public function APIgetProductsList() {
$token = $this->_getToken();
$client = $this->_getClient();
$products = $client->call($token, self::PRODUCTS_LIST );
return $this->_apiJsonResult( $products );
}
You need to create your own api by creating new module then you can use that api method refer this link http://www.magentocommerce.com/wiki/5_-_modules_and_development/web_services/custom_api_complete_example
i have a LoginController like this:
public function loginAction(){
$db = $this->_getParam('db');
$this->_helper->viewRenderer->setNoRender();
$this->_helper->getHelper('layout')->disableLayout();
$adapter = new Zend_Auth_Adapter_DbTable(
$db,
'user',
'username',
'password',
'MD5(CONCAT(?,password_salt))'
);
$adapter->setIdentity($this->_request->getParam('username'));
$adapter->setCredential($this->_request->getParam('password'));
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
// get all info about this user from the login table ommit only the password, we don't need that
$userInfo = $adapter->getResultRowObject(null, 'password');
$users = new Application_Model_DbTable_Users();
$users->updateLastlogin($userInfo->email);
$auth->setStorage(new Zend_Auth_Storage_Session('testzf'));
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);
$data = array('login'=>'success');
}
and a ProfileController:
public function getprofileAction(){
$this->_helper->viewRenderer->setNoRender();
$this->_helper->getHelper('layout')->disableLayout();
if(Zend_Auth::getInstance()->hasIdentity()) {
$username=$this->_request->getParam('username');
$db_users = new Application_Model_DbTable_Users();
$user = $db_users->getUser($username);
}
i made AjaxCalls for both Login and getprofile actions. I can login but getprofile doesn't work because Zend_Auth::getInstance()->hasIdentity() returns null.
I see 2 session files in the folder as in application.ini. resources.session.save_path = APPLICATION_PATH "/../data/sessions"
First one is full of session data, the second one is empty 0KB.
Should this work through Ajax-Calls or i make an Error?
Regards
Since you've used a custom auth storage key in your login action (testzf), you'll need to set this whenever you want to access the auth data:
public function getprofileAction(){
$this->_helper->viewRenderer->setNoRender();
$this->_helper->getHelper('layout')->disableLayout();
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('testzf'));
if($auth->hasIdentity()) {
$username=$this->_request->getParam('username');
$db_users = new Application_Model_DbTable_Users();
$user = $db_users->getUser($username);
}
}
Please use Zend_Auth_Storage_Session like
in your login action
// check ajax request
$result = array(
'error' => true,
'msg' => 'Something went wrong,please try again!'
);
if(!$this->_request->isXmlHttpRequest()){
$this->_helper->json->sendJson($result);
}
/**
* user authentication
*/
$authAdapter = new Zend_Auth_Adapter_DbTable(null,$this->_table_user);
$authAdapter->setIdentityColumn('user_name')
->setCredentialColumn('password');
$authAdapter->setIdentity($user_name)
->setCredential($password);
$select = $authAdapter->getDbSelect();
$select->where('status = ?',1);
$result = $authAdapter->authenticate($authAdapter);
/**
* user validate
*/
if($result->isValid()){
$userStorage = new Zend_Auth_Storage_Session('Zend_Auth_User','User_Storage');
$userData = $authAdapter->getResultRowObject();
$userStorage->write($userData );
$this->_helper->json->sendJson(array('error'=>false));
}
// in your profile action
/**
* you will get user session data through Zend_Auth_Storage_Session
* you can write this function in action controller you will get in your controller easily
like $this->_helper->json->sendJson(array('error'=>false));
*/
$userStorage = new Zend_Auth_Storage_Session('Zend_Auth_User','User_Storage');
$userData = $userStorage->read();
suppose you need to check hasIdentity()
you should use default Zend_Auth_Storage_Session like
$userStorage = new Zend_Auth_Storage_Session();
// default namespace for auth storage (with out any namespace)
you used any namespace for in Zend_Auth_Storage_Session like Zend_Auth_Storage_Session('testzf') you need to set storage in $auth instance like
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('testzf'));
$auth->hasIdentity(); // you will get storage here