encode() public static method

Converts and signs a PHP object or array into a JWT string.
public static encode ( object | array $payload, string $key, string $algo = 'HS256', $keyId = null ) : string
$payload object | array PHP object or array
$key string The secret key
$algo string The signing algorithm. Supported algorithms are 'HS256', 'HS384' and 'HS512'
return string A signed JWT
 public function muestra()
 {
     //$decoded =  JWT::decode($jwt, $this->clave, 'HS256');
     $clave = "beimarhuarachi";
     $user = array('nombre' => 'beimar', 'apellido' => 'huarachi');
     $jwt = JWT::encode($user, $clave, 'HS256');
     echo $jwt;
     echo "Login";
     $ahora = Carbon::now('America/La_Paz');
     $otra = Carbon::now('America/Halifax');
     $hoydia = Carbon::now();
     echo $ahora;
     echo "<br>";
     echo $hoydia;
     echo "<br>";
     echo $otra;
     echo "<br>";
     echo new Carbon('2015-12-12');
     $Y2K = Carbon::create(2000, 1, 1, 0, 0, 0);
     echo "<br>";
     echo $Y2K;
     echo "<br>";
     echo Carbon::parse('2015-02-12 12:00:12');
     //Es para obtener los datos de cualquier peticion(EL CLIENTE TIENE QUE ENVIAR LOS DATOS EN FORMATO JSON)
     //SI NOS ENVIA EN FORMATO DE FORMULARIO EL ACCESO SERIA DIRECTO
     //$entityBody = file_get_contents('php://input');
     //$objeto = json_decode($entityBody);
 }
 public function execute()
 {
     $user = $this->getUser();
     if ($user->isBlocked()) {
         $this->dieUsageMsg('blockedtext');
     }
     if (!$user->isLoggedIn()) {
         $this->dieUsage('Must be logged in', 'token-impossible');
     }
     // Do not fatal out
     if (!class_exists('JWT')) {
         $this->dieUsage('JWT missing', 'token-impossible');
     }
     $config = $this->getConfig()->get('ContentTranslationCXServerAuth');
     $algorithm = $config['algorithm'];
     $key = $config['key'];
     if ($key === '') {
         $this->dieUsage('Key not configured', 'token-impossible');
     }
     $exp = time() + $config['age'];
     $token = array('sub' => $user->getName(), 'iat' => time(), 'exp' => $exp);
     $jwt = JWT::encode($token, $key, $algorithm);
     $this->getResult()->addValue(null, 'jwt', $jwt);
     $this->getResult()->addValue(null, 'exp', $exp);
 }
 public function login($f3, $args)
 {
     self::check_configuration();
     $params = json_decode($f3->get('BODY'));
     if ($params->username && $params->password) {
         $login = new DB\Jig\Mapper($this->db, 'users.json');
         $temp = $login->find(array('(isset(@userName) && @userName == ?)', $params->username));
         if ($temp) {
             $first = __::first($temp);
             if (password_verify($params->password, $first['password'])) {
                 $date = new DateTime();
                 $date->add(new DateInterval('PT' . F3::get('custom.TTL') . 'H'));
                 $out = array('username' => $first['userName'], 'userid' => $first['_id'], 'ttl' => $date->format('Y-m-d H:i:s'), 'roles' => self::get_roles($first['_id']));
                 $jwt = JWT::encode($out, F3::get('custom.SUPER-KEY'));
                 echo json_encode(array('token' => $jwt, 'data' => array('firstName' => $first['firstName'], 'lastName' => $first['lastName'], 'userName' => $first['userName'])));
             } else {
                 self::wrong_login();
             }
         } else {
             self::wrong_login();
         }
     } else {
         self::wrong_login();
     }
 }
Example #4
0
    /**
     * $scopes: should be an array with the follow structure:
     *
     *          'scope' => [
     *              'actions' => ['action1', 'action2']
     *          ],
     *          'scope2' => [
     *              'actions' => ['action1', 'action2']
     *          ]
     */
    public static function encode($client_id, $client_secret, $scopes = null, $custom_payload = null, $lifetime = 36000) {

            $time = time();

            $payload = array(
                "iat" => $time,
            );

            if ($scopes) {
                $payload["scopes"] = $scopes;
            }

            if ($scopes) {
                $custom_payload = array_merge($custom_payload, $payload);
            }

            $jti = md5(json_encode($payload));

            $payload['jti'] = $jti;
            $payload["exp"] = $time + $lifetime;
            $payload["aud"] = $client_id;

            $secret = base64_decode(strtr($client_secret, '-_', '+/'));

            $jwt = \JWT::encode($payload, $secret);

            return $jwt;


    }
 /**
  * @access  public
  * @param   array|object $data     An object or array of data you wish
  *                                 to associate with the token. It will
  *                                 be available as the variable "auth" in
  *                                 the Firebase rules engine.
  * @param   object       $options  Optional. An associative array with
  *                                 the developer supplied options for this
  *                                 token. The following keys are recognized:
  *
  *                                   'admin': Set to true if you want this
  *                                   token to bypass all security rules.
  *                                   Defaults to false.
  *
  *                                   'debug': Set to true if you want to
  *                                   enable debug output from your security
  *                                   rules.
  *
  *                                   'expires': Set to a number (seconds
  *                                   since epoch) or a DateTime object that
  *                                   specifies the time at which the token
  *                                   should expire.
  *
  *                                   'notBefore': Set to a number (seconds
  *                                   since epoch) or a DateTime object that
  *                                   specifies the time before which the
  *                                   should be rejected by the server.
  *                                   
  *
  * @return  string       A Firebase auth token.
  */
 public function createToken($data, $options = null)
 {
     $funcName = 'Services_FirebaseTokenGenerator->createToken';
     // If $data is JSONifiable, let it pass.
     $json = json_encode($data);
     if (function_exists("json_last_error") && ($errno = json_last_error())) {
         $this->handleJSONError($errno);
     } else {
         if ($json === "null" && $data !== null) {
             throw new UnexpectedValueException("Data is not valid JSON");
         } else {
             if (empty($data) && empty($options)) {
                 throw new Exception($funcName + ": data is empty and no options are set.  This token will have no effect on Firebase.");
             }
         }
     }
     $claims = array();
     if (is_array($options)) {
         $claims = $this->_processOptions($options);
     }
     $claims["d"] = $data;
     $claims["v"] = $this->version;
     $claims["iat"] = time();
     return JWT::encode($claims, $this->secret, "HS256");
 }
Example #6
0
 public function login()
 {
     if ($this->input->is_ajax_request()) {
         if (!$this->input->post("email") || !$this->input->post("password")) {
             echo json_encode(array("code" => 2, "response" => "Datos insuficientes"));
         }
         $email = $this->input->post("email");
         $password = sha1($this->input->post("password"));
         $this->load->model("auth_model");
         //$user = $this->auth_model->login($email, $password);
         $this->db->select('id, email');
         $this->db->from('accounts');
         $this->db->where('email', $email);
         $this->db->where('password', $password);
         $user = $this->db->get()->row();
         if ($user) {
             $user->iat = time();
             $user->exp = time() + 20;
             $jwt = JWT::encode($user, 'appTokenKey');
             echo json_encode(array("code" => 0, "response" => array("token" => $jwt)));
         } else {
             echo json_encode(array("response" => array("errorLogin" => 'Usuario o contrasena incorrectos.')));
         }
     } else {
         show_404();
     }
 }
Example #7
0
    function onAfterOrderConfirm(&$order, &$methods, $method_id)
    {
        parent::onAfterOrderConfirm($order, $methods, $method_id);
        if ($this->payment_params->testingMode == true) {
            $this->payment_params->url = "https://sandbox.google.com/checkout/inapp/lib/buy.js";
        } else {
            $this->payment_params->url = "https://wallet.google.com/inapp/lib/buy.js";
        }
        if (empty($this->payment_params->sellerIdentifier)) {
            $this->app->enqueueMessage('You have to configure an seller Identifier for the googlewallet plugin payment first : check your plugin\'s parameters,
			on your website backend', 'error');
            return false;
        }
        if (empty($this->payment_params->sellerSecret)) {
            $this->app->enqueueMessage('You have to configure the seller Secret for the googlewallet plugin payment first : check your plugin\'s parameters,
			on your website backend', 'error');
            return false;
        }
        $amount = round($order->cart->full_total->prices[0]->price_value_with_tax, 2);
        $succes_url = HIKASHOP_LIVE . 'index.php?option=com_hikashop&ctrl=checkout&task=after_end&order_id=' . $order->order_id . $this->url_itemid;
        $cancel_url = HIKASHOP_LIVE . 'index.php?option=com_hikashop&ctrl=order&task=cancel_order&order_id=' . $order->order_id . $this->url_itemid;
        $this->payment_params->succes_url = $succes_url;
        $this->payment_params->cancel_url = $cancel_url;
        $vars = array('iss' => trim($this->payment_params->sellerIdentifier), 'aud' => "Google", 'typ' => "google/payments/inapp/item/v1", 'exp' => time() + 3600, 'iat' => time(), 'request' => array('name' => $order->order_number, 'description' => "", 'price' => $amount, 'currencyCode' => $this->currency->currency_code, 'sellerData' => $order->order_id));
        $sellerSecret = $this->payment_params->sellerSecret;
        $token = JWT::encode($vars, $sellerSecret);
        $this->token = $token;
        $this->showPage('end');
        if ($this->payment_params->debug) {
            $this->writeToLog("Data send to googlewallet: \n\n\n" . print_r($vars, true));
        }
    }
Example #8
0
 /**
  * Converts and signs a PHP object or array into a JWT string.
  *
  * @param object|array $payload PHP object or array
  * @param string|null  $alg     The signing algorithm. Supported
  *                              algorithms are 'HS256', 'HS384' and 'HS512'
  *
  * @return string      A signed JWT
  */
 public function encode($payload, $alg = null)
 {
     if (empty($alg)) {
         $alg = $this->alg;
     }
     return \JWT::encode($payload, $this->key, $alg);
 }
Example #9
0
 /**
  * @access  public
  * @param   array|object $data     An object or array of data you wish
  *                                 to associate with the token. It will
  *                                 be available as the variable "auth" in
  *                                 the Firebase rules engine.
  * @param   object       $options  Optional. An associative array with
  *                                 the developer supplied options for this
  *                                 token. The following keys are recognized:
  *
  *                                   'admin': Set to true if you want this
  *                                   token to bypass all security rules.
  *                                   Defaults to false.
  *
  *                                   'debug': Set to true if you want to
  *                                   enable debug output from your security
  *                                   rules.
  *
  *                                   'expires': Set to a number (seconds
  *                                   since epoch) or a DateTime object that
  *                                   specifies the time at which the token
  *                                   should expire.
  *
  *                                   'notBefore': Set to a number (seconds
  *                                   since epoch) or a DateTime object that
  *                                   specifies the time before which the
  *                                   should be rejected by the server.
  *
  *
  * @return  string       A Firebase auth token.
  */
 public function createToken($data, $options = null)
 {
     $funcName = 'Services_FirebaseTokenGenerator->createToken';
     // If $data is JSONifiable, let it pass.
     $json = json_encode($data);
     if (function_exists("json_last_error") && ($errno = json_last_error())) {
         $this->handleJSONError($errno);
     } else {
         if ($json === "null" && $data !== null) {
             throw new UnexpectedValueException("Data is not valid JSON");
         } else {
             if (empty($data) && empty($options)) {
                 throw new Exception($funcName . ": data is empty and no options are set.  This token will have no effect on Firebase.");
             }
         }
     }
     $claims = array();
     if (is_array($options)) {
         $claims = $this->_processOptions($options);
     }
     $this->_validateData($funcName, $data, isset($claims['admin']) && $claims["admin"] == true);
     $claims["d"] = $data;
     $claims["v"] = $this->version;
     $claims["iat"] = time();
     $token = JWT::encode($claims, $this->secret, "HS256");
     if (strlen($token) > 1024) {
         throw new Exception($funcName . ": generated token is too large.  Token cannot be larger than 1024 bytes.");
     }
     return $token;
 }
Example #10
0
 public function login()
 {
     // check ajax request
     if ($this->input->is_ajax_request()) {
         // check post parameter
         if (!$this->input->post("username") || !$this->input->post("password")) {
             echo json_encode(array("code" => 2, "response" => "Data insufficient"));
         }
         $uname = $this->input->post("username");
         $password = $this->input->post("password");
         // check login
         $user = $this->Login_mdl->login($uname, $password);
         // $sid=$this->Login_mdl->addsession($user->user_id,$user->user_name,$user->db_pass);
         if ($user !== false) {
             $chksesstbl = $this->Login_mdl->check_active_user($user->user_id);
             if ($chksesstbl) {
                 $this->Login_mdl->reset_active_session($user->user_id);
             }
             $sessionid = session_id();
             $sid = $this->Login_mdl->add_new_session($user->user_id, $sessionid);
             $user->iat = time();
             $user->exp = time() + 28800000;
             //8 hr extend; default 5000
             $user->sid = $sid;
             //encdoe token
             $jwt = JWT::encode($user, SECRECT_KEY);
             echo json_encode(array("data" => $user, 'token' => $jwt, "status" => array("code" => 0, 'success' => true, 'msg' => $sessionid)));
         } else {
             echo json_encode(array("data" => '', 'token' => '', "status" => array("code" => 0, 'success' => false, 'msg' => '')));
         }
     }
 }
 public static function login(Cart66Account $account)
 {
     $name = $account->firstName . ' ' . $account->lastName;
     $email = $account->email;
     $externalId = $account->id;
     $organization = Cart66Setting::getValue('zendesk_organization');
     $key = Cart66Setting::getValue('zendesk_token');
     $prefix = Cart66Setting::getValue('zendesk_prefix');
     if (Cart66Setting::getValue('zendesk_jwt')) {
         $now = time();
         $token = array("jti" => md5($now . rand()), "iat" => $now, "name" => $name, "email" => $email);
         include_once CART66_PATH . "/pro/models/JWT.php";
         $jwt = JWT::encode($token, $key);
         // Redirect
         header("Location: https://" . $prefix . ".zendesk.com/access/jwt?jwt=" . $jwt);
         exit;
     } else {
         /* Build the message */
         $ts = isset($_GET['timestamp']) ? $_GET['timestamp'] : time();
         $message = $name . '|' . $email . '|' . $externalId . '|' . $organization . '|||' . $key . '|' . $ts;
         $hash = MD5($message);
         $remoteAuthUrl = 'http://' . $prefix . '.zendesk.com/access/remoteauth/';
         $arguments = array('name' => $name, 'email' => $email, 'external_id' => $externalId, 'organization' => $organization, 'timestamp' => $ts, 'hash' => $hash);
         $url = add_query_arg($arguments, $remoteAuthUrl);
         header("Location: " . $url);
         exit;
     }
 }
Example #12
0
 public function getAll()
 {
     // Token para probar el área con seguridad
     $test = array('iat' => time(), 'exp' => time() + LIFETIME, 'security' => 'Security Test');
     $jwt = JWT::encode($test, TOKEN);
     $this->data = array('mensaje' => 'Hola mundo!!!', 'token' => $jwt);
 }
Example #13
0
 /**
  * Used by the Zendesk single sign on functionality to authenticate users.
  * Only works for admin panel users, not for customers.
  */
 public function authenticateAction()
 {
     if (!Mage::getStoreConfig('zendesk/sso/enabled')) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Single sign-on disabled.'));
         $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl());
     }
     $domain = Mage::getStoreConfig('zendesk/general/domain');
     $token = Mage::getStoreConfig('zendesk/sso/token');
     if (!Zend_Validate::is($domain, 'NotEmpty')) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Zendesk domain not set. Please add this to the settings page.'));
         $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl());
     }
     if (!Zend_Validate::is($token, 'NotEmpty')) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Zendesk SSO token not set. Please add this to the settings page.'));
         $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl());
     }
     $now = time();
     $jti = md5($now . rand());
     $user = Mage::getSingleton('admin/session')->getUser();
     $name = $user->getName();
     $email = $user->getEmail();
     $externalId = $user->getId();
     $payload = array("iat" => $now, "jti" => $jti, "name" => $name, "email" => $email, "external_id" => $externalId);
     Mage::log('Admin JWT: ' . var_export($payload, true), null, 'zendesk.log');
     $jwt = JWT::encode($payload, $token);
     $url = "http://" . $domain . "/access/jwt?jwt=" . $jwt;
     Mage::log('Admin URL: ' . $url, null, 'zendesk.log');
     $this->_redirectUrl($url);
 }
Example #14
0
 public static function getToken($user)
 {
     //@todo, check to see if we have a token stored for this user
     $key = Settings::get('hash_salt');
     $token = array("uid" => $user->id(), "mail" => $user->getEmail());
     return \JWT::encode($token, $key);
 }
Example #15
0
 function loginset($id)
 {
     $userinfo = $this->User_data->userinfo($id);
     //读取用户数据
     //多说账号
     $token = array("short_name" => 'zustmanager', "user_key" => $userinfo['student_id'], "name" => $userinfo['username']);
     $duoshuoToken = JWT::encode($token, '97c1b8a2ce9f394b034232572c086196');
     $cookie = array('name' => 'duoshuo_token', 'value' => $duoshuoToken, 'expire' => '86500', 'domain' => '', 'path' => '/', 'secure' => FALSE);
     $this->input->set_cookie($cookie);
     $userinfo_session = array('username' => $userinfo['username'], 'student_id' => $userinfo['student_id'], 'head_img' => $userinfo['head_img'], 'major' => $userinfo['major'], 'classnum' => $userinfo['classnum'], 'email' => $userinfo['email'], 'qq' => $userinfo['qq']);
     $this->session->set_userdata($userinfo_session);
     //将用户数据写入session
     $logindate = array('status' => "1", 'lastLoginTime' => date("Y-m-d H:i:s"));
     $this->db->from('user')->where('student_id', $id)->update('user', $logindate);
     //更新用户登陆时间
     $log = array('student_id' => $userinfo['student_id'], 'username' => $userinfo['username'], 'events' => '登陆', 'time' => date("Y-m-d H:i:s"));
     $this->db->insert('log', $log);
     //记录事件 登陆
     /*      print_r($userinfo);//用户数据调出 调试用
     						echo "<hr>";
     						echo $this->session->userdata('username');
     						echo "<hr>";
     						echo "查询到此人";
     						echo date("Y-m-d H:i:s");*/
     $cookie = array('name' => 'zust_login', 'value' => $userinfo['student_id'] . '&' . $userinfo['password'], 'expire' => '86500', 'domain' => '', 'path' => '/', 'secure' => FALSE);
     $this->input->set_cookie($cookie);
     redirect(base_url('user/profile'));
 }
Example #16
0
 public function login()
 {
     $res = new stdClass();
     $res->success = FALSE;
     $data = new stdClass();
     parse_str(file_get_contents("php://input"), $data);
     $data = (object) $data;
     $this->load->model('sp_model');
     $where = 'userName="******"';
     $arr = $this->sp_model->where('jwt_user', $where, 'id', 'asc');
     if (count($arr) == 1) {
         if (Password::validate_password($data->password, $arr[0]->password)) {
             $res->success = true;
             $token = array();
             $token['id'] = $arr[0]->id;
             $res->access_token = JWT::encode($token, $this->config->item('jwt_key'));
             $res->id = $arr[0]->id;
         } else {
             $res->error = 'Invalid user name or password.';
             http_response_code(401);
         }
     } else {
         $res->error = 'Invalid user name or password.';
         http_response_code(401);
     }
     $this->load->view('json', array('output' => $res));
 }
Example #17
0
 function testKIDChooser()
 {
     $keys = array('1' => 'my_key', '2' => 'my_key2');
     $msg = JWT::encode('abc', $keys['1'], 'HS256', '1');
     $decoded = JWT::decode($msg, $keys, true);
     $this->assertEquals($decoded, 'abc');
 }
Example #18
0
 public function token()
 {
     $user = $this->Auth->identify();
     if (!$user) {
         throw new UnauthorizedException('Invalid username or password');
     }
     $this->set(['success' => true, 'data' => ['token' => $token = \JWT::encode(['id' => $user['id'], 'exp' => time() + 604800], Security::salt())], '_serialize' => ['success', 'data']]);
 }
 public function token()
 {
     $user = $this->Auth->identify();
     if (!$user) {
         throw new UnauthorizedException('Invalid username or password');
     }
     $this->set('data', ['user' => $user, 'token' => $token = \JWT::encode(['id' => $user['id'], 'user' => $user, 'exp' => time() + 604800], Security::salt())]);
     $this->ApiBuilder->execute();
 }
Example #20
0
 /**
  * @return void 
  */
 function init()
 {
     $expiry = 48 * 60 * 60;
     $sub = $this->serviceID . ":" . $this->userID;
     $exp = time() + $expiry;
     $apisecret = $this->apiSecret;
     $apiSecretKey = JWT::urlsafeB64Decode($apisecret);
     $payload = array("sub" => $sub, "iss" => $this->serviceID, "exp" => $exp);
     $this->jwt = JWT::encode($payload, $apiSecretKey);
 }
Example #21
0
function createToken($user, $roles, $competitions)
{
    $key = "supersecret";
    $date = new DateTime();
    $teams = [array('TeamID' => 1, 'TeamName' => 'Bornerbroek 3'), array('TeamID' => 27, 'TeamName' => 'Bornerbroek 4')];
    $seasons = [array('SeasonID' => 3, 'Description' => '2015-2016')];
    $token = array("iat" => $date->getTimestamp(), "exp" => $date->getTimestamp() + 86400, "username" => $user["Name"], "roles" => $roles, "competitions" => $competitions, "seasons" => $seasons, "defaultSeasonID" => 3, "teams" => $teams);
    $jwt = JWT::encode($token, $key);
    return $jwt;
}
 static function from_user($user, $max_age = LFTOKEN_MAX_AGE)
 {
     $secret = $user->get_domain()->get_key();
     $args = array('domain' => $user->get_domain()->get_host(), 'user_id' => $user->get_uid(), 'expires' => time() + $max_age);
     $dname = $user->get_display_name();
     if (!empty($dname)) {
         $args['display_name'] = $dname;
     }
     return JWT::encode($args, $secret);
 }
Example #23
0
function setUserToken($user, $expires)
{
    $token = JWT::encode(array('exp' => time() + $expires, 'uid' => $user->id), getJwtKey());
    $dbToken = R::dispense('token');
    $dbToken->token = $token;
    if (null == $user->ownToken) {
        $user->ownToken = [];
    }
    $user->ownToken[] = $dbToken;
    R::store($user);
}
 public function generate($scopes, $lifetime = 36000)
 {
     $time = time();
     $payload = array("iat" => $time, "scopes" => $scopes);
     $jti = md5(json_encode($payload));
     $payload['jti'] = $jti;
     $payload["exp"] = $time + $lifetime;
     $payload["aud"] = $this->client_id;
     $secret = base64_decode(strtr($this->client_secret, '-_', '+/'));
     $jwt = \JWT::encode($payload, $secret);
     return $jwt;
 }
 public function setJWTToken($arrParams)
 {
     $token = array();
     $token['iss'] = "refermee.com";
     $token['exp'] = $this->getTokenExpTime();
     $token['aud'] = $arrParams["email"] . $arrParams["userid"] . "_refermee_auth";
     foreach ($arrParams as $key => $value) {
         $token[$key] = $value;
     }
     $encodedToken = \JWT::encode($token, $this->secret);
     return $encodedToken;
 }
 function go_login()
 {
     $this->load->helper('security');
     $this->load->helper('authen_helper');
     $msg = '';
     // validate form
     $this->load->library('form_validation');
     $this->form_validation->set_rules('username', 'username', 'trim|required|alpha_dash');
     $this->form_validation->set_rules('password', 'password', 'trim|required|no_space');
     $remember = $this->input->post('remember');
     if ($this->form_validation->run() == FALSE) {
         $msg = 'ข้อมูลไม่ถูกต้อง';
         $this->session->set_flashdata('msg', $msg);
         redirect('/shop/login');
         return;
     }
     $usr = set_value('username');
     $pwd = do_hash(set_value('password'), 'sha256');
     $dealer = $this->Dealer->get_dealer_by_login($usr, $pwd);
     // if login success
     if ($dealer != NULL) {
         //set user data to session
         $this->session->set_userdata($dealer);
         // if remember
         $c = 0;
         // if server too slow
         while (!check_login()) {
             $c++;
             sleep(1);
             if ($c >= 5) {
                 redirect('/shop/login');
                 return;
             }
         }
         if ($remember) {
             // if remember, then set JWT
             $payload = array('iss' => base_url(), 'exp' => time() + $this->exp, 'dealer_id' => $this->session->userdata('dealer_id'), 'dealer_agent' => $this->session->userdata('user_agent'));
             // encode JWT
             $tok = JWT::encode($payload, $this->config->item('JWT_KEY'));
             // set cookie
             $cookie_arr = array('name' => COOK_USER_NAME, 'value' => $tok, 'expire' => $this->exp);
             $this->input->set_cookie($cookie_arr);
         }
         redirect('/shop');
         return;
     } else {
         $msg = "username หรือ password ไม่ถูกต้อง<br/>หรือบัญชีอาจยังไม่ได้รับการยืนยันจากทางร้าน";
     }
     $this->session->set_flashdata('username', $usr);
     $this->session->set_flashdata('msg', $msg);
     redirect('/shop/login');
 }
Example #27
0
 public function toJWT($algorithm = 'HS256')
 {
     $header = array('cty' => 'twilio-fpa;v=1', 'typ' => 'JWT');
     $now = time();
     $grants = array();
     if ($this->identity) {
         $grants['identity'] = $this->identity;
     }
     foreach ($this->grants as $grant) {
         $grants[$grant->getGrantKey()] = $grant->getPayload();
     }
     $payload = array('jti' => $this->signingKeySid . '-' . $now, 'iss' => $this->signingKeySid, 'sub' => $this->accountSid, 'nbf' => $now, 'exp' => $now + $this->ttl, 'grants' => $grants);
     return JWT::encode($payload, $this->secret, $algorithm, $header);
 }
 public function create(\Stormpath\Resource\Account $account)
 {
     $refreshTokenCookieConfig = config('stormpath.web.refreshTokenCookie');
     $application = app('stormpath.application');
     try {
         $jwt = \JWT::encode(['sub' => $account->href, 'iat' => time() - 1, 'status' => 'AUTHENTICATED', 'iss' => $application->href, 'aud' => config('stormpath.client.apiKey.id')], config('stormpath.client.apiKey.secret'), 'HS256');
         $idSiteRequest = new IdSiteRequest();
         $idSiteRequest->stormpathToken = $jwt;
         $idSiteRequest->grantType = 'stormpath_token';
         return app('stormpath.client')->getDataStore()->create($application->href . '/oauth/token', $idSiteRequest, Stormpath::ACCESS_TOKEN);
     } catch (\Exception $e) {
         throw new SocialLoginException($e->getMessage());
     }
 }
Example #29
0
/**
 * @param string $key
 * @param string $aud
 * @param string $iss
 * @param array $addl_payload_params
 * @return string
 */
function createNewToken($key, $aud, $iss, $addl_payload_params = array())
{
    $now = new \DateTime('now');
    $expires = new \Datetime('now');
    $expires->add(new \DateInterval("P42D"));
    // sets token expiration date to six weeks from now
    $payload = array();
    $payload['iat'] = $now->format('U');
    $payload['exp'] = $expires->format('U');
    $payload['iss'] = $iss;
    $payload['aud'] = $aud;
    $payload = array_merge($payload, $addl_payload_params);
    return JWT::encode($payload, $key);
}
Example #30
-1
 function is_authenticated($user)
 {
     $CI =& get_instance();
     $CI->load->library('JWT');
     $CI->input->get_request_header('Authorization');
     return JWT::encode($token, JWT_TOKEN_SECRET);
 }