/**
  * Authenticate users based on their JWT. This is inspired by
  * the method _findUser in admads JWT plugin
  *
  * @see https://github.com/ADmad/cakephp-jwt-auth/blob/master/src/Auth/JwtAuthenticate.php
  * @param string $token The token identifier.
  * @param mixed $extra Unused
  * @return array
  */
 public function processAuthenticate($token, $extra = null)
 {
     try {
         $token = JWT::decode($token, Security::salt(), Configure::read('Websockets.allowedAlgs'));
     } catch (Exception $e) {
         if (Configure::read('debug')) {
             throw $e;
         }
         return ["FAILURE"];
     }
     if ($token->id == 'server') {
         return ["SUCCESS", ["authid" => $token->id]];
     }
     $fields = Configure::read('Websockets.fields');
     $table = TableRegistry::get(Configure::read('Websockets.userModel'));
     $conditions = [$table->aliasField($fields['id']) => $token->id];
     if (!empty(Configure::read('Websockets.scope'))) {
         $conditions = array_merge($conditions, Configure::read('Websockets.scope'));
     }
     $result = $table->find('all')->where($conditions)->first();
     if (empty($result)) {
         return ["FAILURE"];
     }
     return ["SUCCESS", ["authid" => $result->id]];
 }
 /**
  * Initialize config data and properties.
  *
  * @param array $config The config data.
  * @return void
  */
 public function initialize(array $config)
 {
     if (!$this->_config['cypherKey']) {
         $this->config('cypherKey', Security::salt());
     }
     $this->Cookie->configKey($this->config('cookieName'), ['key' => $this->config('cypherKey'), 'expires' => $this->config('period')]);
 }
Ejemplo n.º 3
0
 /**
  * Get URL builder instance.
  *
  * @return \League\Urls\UrlBuilder URL builder instance.
  */
 public function urlBuilder()
 {
     if (!isset($this->_urlBuilder)) {
         $this->_urlBuilder = UrlBuilderFactory::create(Configure::read('Glide.serverConfig.base_url'), Configure::read('Glide.secureUrls') ? Security::salt() : null);
     }
     return $this->_urlBuilder;
 }
Ejemplo n.º 4
0
 /**
  * Index Login method  API URL  /api/login method: POST
  * @return json response
  */
 public function login()
 {
     try {
         $user = $this->Auth->identify();
         if ($user) {
             $user = $this->Users->get($user['id']);
             if (!$user) {
             }
         } else {
             throw new UnauthorizedException("Invalid login");
         }
         // Generate user Auth token
         $authentication = $this->Authentications->newEntity();
         $authentication->auth_token = Security::hash($user->id . $user->email, 'sha1', true);
         $authentication->user_id = $user->id;
         $authentication->ip = $this->request->clientIp();
         $this->Authentications->save($authentication);
         $this->Auth->setUser($user->toArray());
     } catch (UnauthorizedException $e) {
         throw new UnauthorizedException($e->getMessage(), 401);
     }
     $this->set('user', $this->Auth->user());
     $this->set('token', $authentication->auth_token);
     $this->set('_serialize', ['user', 'token']);
 }
 /**
  * Purge ConnectionManager configs.
  *
  * @return void
  */
 public static function tearDownAfterClass()
 {
     foreach (self::$datasources as $ds => $configs) {
         \Cake\Datasource\ConnectionManager::drop($ds);
     }
     \Cake\Utility\Security::salt('');
 }
Ejemplo n.º 6
0
 /**
  * Marshalls request data into PHP strings.
  *
  * @param mixed $value The value to convert.
  * @return mixed Converted value.
  */
 public function marshal($value)
 {
     if ($value === null) {
         return $value;
     }
     return base64_encode(Security::encrypt($value, Configure::read('Security.key')));
 }
Ejemplo n.º 7
0
 function ajax_login()
 {
     if ($this->request->is('ajax')) {
         $email = $this->request->data['email'];
         $password = Security::hash($this->request->data['password'], 'sha1', true);
         $user = $this->Users->find()->where(['email' => $email, 'password' => $password, 'status <>' => USER_STATUS_DELETED])->first();
         if ($user) {
             if ($user->status == USER_STATUS_ACTIVE) {
                 $user->auth_token = \Core::randomCode();
                 // if 'remember me' checked, save cookie
                 /*if(isset($this->request->data['User']['remember']))
                   {
                       $this->Cookie->write('CookieRemember', $user->auth_token, null, '30 days');
                   }
                   else
                   {
                       $this->Cookie->delete('CookieRemember');
                   }*/
                 if ($this->Users->save($user)) {
                     $this->request->session()->write('Core.Users', $user);
                     $this->ajax['status'] = AJAX_STATUS_SUCCESS;
                     $this->ajax['redirect'] = $this->request->webroot . 'admin/users/index';
                 }
             } else {
                 $this->ajax['status'] = AJAX_STATUS_ERROR;
                 $this->ajax['error'] = __('your account has been blocked');
             }
         } else {
             $this->ajax['status'] = AJAX_STATUS_ERROR;
             $this->ajax['error'] = __('invalid email or password');
         }
     }
 }
Ejemplo n.º 8
0
 /**
  * Callback for Routing.beforeDispatch event.
  *
  * @param \Cake\Event\Event $event The event instance.
  *
  * @return \Cake\Network\Response Response instance.
  */
 public function beforeDispatch(Event $event)
 {
     $request = $event->data['request'];
     $response = $event->data['response'];
     $path = urldecode($request->url);
     if (Configure::read('Glide.secureUrls')) {
         SignatureFactory::create(Security::salt())->validateRequest('/' . $path, $request->query);
     }
     $server = ServerFactory::create(Configure::read('Glide.serverConfig'));
     $cache = Configure::read('Glide.cache');
     if ($cache) {
         $timestamp = $server->getSource()->getTimestamp($server->getSourcePath($path));
         $response->modified($timestamp);
         if (!$response->checkNotModified($request)) {
             $response = $server->getImageResponse($path, $request->query);
         }
         $response->cache($timestamp, $cache);
     } else {
         $response = $server->getImageResponse($path, $request->query);
     }
     $headers = Hash::filter((array) Configure::read('Glide.headers'));
     foreach ($headers as $key => $value) {
         $response->header($key, $value);
     }
     return $response;
 }
Ejemplo n.º 9
0
 public function setContentsFile()
 {
     $this->__contentsFileSettings();
     foreach ($this->__contentsFileSettings['fields'] as $field => $field_setting) {
         $file_info = $this->{$field};
         if (!empty($file_info) && array_key_exists('error', $file_info) && $file_info['error'] != UPLOAD_ERR_NO_FILE) {
             $file_set = ['model' => $this->_registryAlias, 'model_id' => $this->id, 'field_name' => $field, 'file_name' => $file_info['name'], 'file_content_type' => $file_info['type'], 'file_size' => $file_info['size'], 'file_error' => $file_info['error']];
             //$file_infoにtmp_nameがいるときはtmpディレクトリへのファイルのコピーを行う
             if (!empty($file_info['tmp_name'])) {
                 $tmp_file_name = Security::hash(rand() . Time::now()->i18nFormat('YYYY/MM/dd HH:ii:ss') . $file_info['name']);
                 if ($this->__getExt($file_info['name']) !== null) {
                     $tmp_file_name .= '.' . $this->__getExt($file_info['name']);
                 }
                 if (!copy($file_info['tmp_name'], $field_setting['cacheTempDir'] . $tmp_file_name)) {
                     //エラー
                 }
                 $file_set['tmp_file_name'] = $tmp_file_name;
             }
             //これを残して次に引き渡したくないので
             unset($this->{$field});
             $this->{'contents_file_' . $field} = $file_set;
         }
     }
     return $this;
 }
Ejemplo n.º 10
0
 /**
  * setUp
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Security::salt('12345678901234567890123456789012345678901');
     $this->controller = new Controller(new Request(), new Response());
     $this->controller->loadComponent('Cookie');
     $this->controller->loadComponent('Auth');
 }
Ejemplo n.º 11
0
 public function beforeSave(Event $event)
 {
     $entity = $event->data['entity'];
     if ($entity->isNew()) {
         $entity->api_key = Security::hash(Text::uuid());
     }
     return true;
 }
Ejemplo n.º 12
0
 /**
  * Test marshalling
  *
  * @return void
  */
 public function testMarshal()
 {
     $this->assertNull($this->type->marshal(null));
     $encrypted = $this->type->marshal('string');
     $this->assertSame(128, strlen($encrypted));
     $decrypted = Security::decrypt(base64_decode($encrypted), Configure::read('Security.key'));
     $this->assertSame('string', $decrypted);
 }
Ejemplo n.º 13
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']]);
 }
Ejemplo n.º 14
0
 /**
  * Get the boundary marker
  *
  * @return string
  */
 public function boundary()
 {
     if ($this->_boundary) {
         return $this->_boundary;
     }
     $this->_boundary = md5(Security::randomBytes(16));
     return $this->_boundary;
 }
Ejemplo n.º 15
0
 /**
  * Signs the url with a salted hash
  *
  * @throws \RuntimeException
  * @param array $options
  * @return string
  */
 public function hash($options)
 {
     $mediaSalt = Configure::read('Imagine.salt');
     if (empty($mediaSalt)) {
         throw new \RuntimeException(__d('imagine', 'Please configure {0} using {1}', 'Imagine.salt', 'Configure::write(\'Imagine.salt\', \'YOUR-SALT-VALUE\')'));
     }
     ksort($options);
     return urlencode(Security::hash(serialize($options) . $mediaSalt));
 }
 public function login($provider = null)
 {
     if ($provider) {
         $config = ['path' => Router::url(['action' => 'login']) . '/', 'callback_url' => Router::url(['action' => 'callback']), 'security_salt' => Security::salt(), 'Strategy' => Configure::read('OpauthStrategy')];
         $opauth = new \Opauth($config, true);
     } else {
         throw new NotFoundException();
     }
 }
Ejemplo n.º 17
0
 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();
 }
Ejemplo n.º 18
0
 /**
  * Tries to decode, decrypt and unserialize the given token and return the data as an
  * array
  *
  * @param string $token The string token
  * @return array|false
  */
 public function decryptToken($token)
 {
     $tokenData = false;
     $encrypted = base64_decode($token);
     if ($encrypted) {
         $serialized = Security::decrypt($encrypted, Configure::read('Security.cryptKey'));
         $tokenData = unserialize($serialized);
     }
     return $tokenData;
 }
Ejemplo n.º 19
0
 public function google()
 {
     $data = $this->request->input('json_decode');
     $user = $this->Users->find('all')->where(['Users.provider' => 'facebook', 'Users.provider_uid' => $data->clientId])->first();
     if (!$user) {
         throw new UnauthorizedException('Invalid username or password');
     }
     $this->Auth->setUser($user);
     $this->set(['success' => true, 'data' => ['token' => JWT::encode(['sub' => $user['id'], 'exp' => time() + 1800], Security::salt()), 'user_id' => $user['id']], '_serialize' => ['success', 'data']]);
 }
 public function createToken()
 {
     $customer = $this->Customers->find('all', ['fields' => ['id', 'email', 'name', 'password'], 'conditions' => ['email' => $this->request->data('email'), 'gym_id' => $this->request->query('gym_id'), 'deleted' => false, 'is_active' => true]])->first();
     if (!$customer || !(new DefaultPasswordHasher())->check($this->request->data('password'), $customer->password)) {
         throw new UnauthorizedException('Invalid username or password');
     }
     $customer->sub = $customer->id;
     unset($customer->password);
     $this->set(['message' => ['user' => ['name' => $customer->name], 'token' => JWT::encode($customer->toArray(), Security::salt())]]);
     $this->set('_serialize', ['message']);
 }
Ejemplo n.º 21
0
 public function testValueIsAddedToDatabaseWithEncryption()
 {
     $value = '555';
     $store = MapStore::load('2');
     $store->set('access_token', $value);
     $entity = $this->Model->get(['2', 'access_token']);
     $dbValue = stream_get_contents($entity->value);
     $dbValueDecrypted = Security::decrypt($dbValue, Configure::read('Security.key'), Configure::read('Security.salt'));
     $this->assertNotEquals($value, $dbValue);
     $this->assertEquals($value, $dbValueDecrypted);
 }
Ejemplo n.º 22
0
 /**
  * Setup
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     Configure::write('App.namespace', 'TestApp');
     Security::salt('not-the-default');
     DispatcherFactory::add('Routing');
     DispatcherFactory::add('ControllerFactory');
     $this->object = $this->getObjectForTrait('Cake\\Routing\\RequestActionTrait');
     Router::connect('/request_action/:action/*', ['controller' => 'RequestAction']);
     Router::connect('/tests_apps/:action/*', ['controller' => 'TestsApps']);
 }
 /**
  * Test initialize method
  *
  * @return void
  */
 public function testInitializeException()
 {
     $salt = Security::salt();
     Security::salt('too small');
     try {
         $this->rememberMeComponent = new RememberMeComponent($this->registry, []);
     } catch (InvalidArgumentException $ex) {
         $this->assertEquals('Invalid app salt, app salt must be at least 256 bits (32 bytes) long', $ex->getMessage());
     }
     Security::salt($salt);
 }
Ejemplo n.º 24
0
 public function login()
 {
     $user = $this->Auth->user();
     if (!$user) {
         $this->request->data('id', (string) $this->request->data('id'));
         if ($this->request->is('put') || $this->request->is('post')) {
             $user = $this->Auth->identify();
         }
     }
     if (!$user) {
         throw new UnauthorizedException('Invalid username or password');
     }
     $this->Auth->setUser($user);
     $this->set(['_serialize' => ['class' => 'Auth', 'token' => JWT::encode(['sub' => $user['id'], 'exp' => time() + 604800], Security::salt()), 'player' => '/players/' . $user['id']]]);
 }
 /**
  * setup
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     $this->request = new Request('posts/index');
     Router::setRequestInfo($this->request);
     $this->response = $this->getMock('Cake\\Network\\Response');
     Security::salt('somerandomhaskeysomerandomhaskey');
     $this->Registry = new ComponentRegistry(new Controller($this->request, $this->response));
     $this->Registry->load('Cookie');
     $this->Registry->load('Auth');
     $this->auth = new CookieAuthenticate($this->Registry, ['fields' => ['username' => 'user_name', 'password' => 'password'], 'userModel' => 'MultiUsers']);
     $password = password_hash('password', PASSWORD_DEFAULT);
     $MultiUsers = TableRegistry::get('MultiUsers');
     $MultiUsers->updateAll(['password' => $password], []);
 }
 /**
  * setup
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     $this->request = new Request('posts/index');
     Router::setRequestInfo($this->request);
     $this->response = $this->getMock('Cake\\Network\\Response');
     Security::salt('Xety-Cake3CookieAuth_Xety-Cake3CookieAuth');
     $this->registry = new ComponentRegistry(new Controller($this->request, $this->response));
     $this->registry->load('Cookie');
     $this->registry->load('Auth');
     $this->auth = new CookieAuthenticate($this->registry);
     $password = password_hash('password', PASSWORD_DEFAULT);
     $Users = TableRegistry::get('Users');
     $Users->updateAll(['password' => $password], []);
 }
Ejemplo n.º 27
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('Auth', ['authenticate' => ['ByuApi', 'CasAuth.Cas' => ['hostname' => 'cas.byu.edu', 'uri' => 'cas']]]);
     $this->loadComponent('AuthUser');
     $this->loadComponent('Flash');
     if ($this->request->query('debug') && !Configure::read('debug')) {
         $user = $this->Auth->user();
         if (!empty($user['roles']['admin'])) {
             $this->loadComponent('Cookie');
             $this->Cookie->configKey('cake_manual_debug', 'encryption', false);
             $this->Cookie->write('cake_manual_debug', $user['username'] . 'debug|' . Security::hash($user['username'] . 'debug'));
         }
     }
 }
Ejemplo n.º 28
0
 /**
  * setUp method
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     $this->backupUsersConfig = Configure::read('Users');
     Router::reload();
     Plugin::routes('CakeDC/Users');
     Router::connect('/route/*', ['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'requestResetPassword']);
     Security::salt('YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
     Configure::write('App.namespace', 'Users');
     $this->request = $this->getMock('Cake\\Network\\Request', ['is', 'method']);
     $this->request->expects($this->any())->method('is')->will($this->returnValue(true));
     $this->response = $this->getMock('Cake\\Network\\Response', ['stop']);
     $this->Controller = new Controller($this->request, $this->response);
     $this->Registry = $this->Controller->components();
     $this->Controller->UsersAuth = new UsersAuthComponent($this->Registry);
 }
Ejemplo n.º 29
0
 public function login()
 {
     $user = $this->Auth->identify();
     if (!$user) {
         $this->set(['success' => false, 'message' => __('Invalid email or password'), '_serialize' => ['success', 'message']]);
     } else {
         $expire = !is_null(Configure::read('AuthToken.expire')) ? Configure::read('AuthToken.expire') : 3600;
         $access_token = JWT::encode(['sub' => $user['id'], 'exp' => time() + $expire], Security::salt());
         $refresh_token = JWT::encode(['sub' => $user['id'], 'ref' => time()], Security::salt());
         $authToken = $this->Users->AuthToken->newEntity();
         $authToken->user_id = $user['id'];
         $authToken->access_token = $access_token;
         $authToken->refresh_token = $refresh_token;
         $this->Users->AuthToken->save($authToken);
         $this->set(['success' => true, 'data' => ['access_token' => $access_token, 'refresh_token' => $refresh_token, 'id' => $user['id'], 'username' => $user['username'], 'email' => $user['email']], '_serialize' => ['success', 'data']]);
     }
 }
 /**
  * Attempting to make a password beefer'upper
  */
 public function index()
 {
     if ($this->request->is(['post', 'put', 'patch'])) {
         $userId = $this->request->session()->read('User.id');
         $this->loadModel('Users');
         $user = $this->Users->get($userId);
         $input = $this->request->data['input'];
         $hash1 = Security::hash($input, 'sha512', $user->username);
         $hash2 = Security::hash($hash1, 'sha512', $user->username . $hash1);
         $hash3 = Security::hash($hash2, 'sha512', $hash2 . $hash1);
         $hash4 = Security::hash($hash3, 'sha512', $hash1 . $hash2);
         $hash5 = Security::hash($hash4, 'sha512', $hash2 . $hash3);
         $hash6 = Security::hash($hash5, 'sha512', $hash3 . $hash4);
         $hash7 = Security::hash($hash6, 'sha512', $hash4 . $hash5);
         $output = $hash7;
         $this->set(compact('output'));
     }
 }