PHP User::addRole Examples

PHP User::addRole - 14 examples found. These are the top rated real world PHP examples of User::addRole extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
 public function testHasRoles()
 {
     $adminRole = new UserRole();
     $adminRole->setName('admin');
     $user = new User();
     $user->addRole($adminRole);
     $this->assertTrue($user->hasRoles(['admin']));
     $this->assertFalse($user->hasRoles(['developer']));
 }
Example #2
0
 /**
  * Вызывается после сохранения в БД
  * @param array $fld
  * @param integer $id
  * @return array
  */
 function ElemRedactAfter($fld, $id)
 {
     global $site_domains;
     $id_user = (int) get('id', 0, 'pg');
     $fld = $_POST['fld'];
     if (!empty($id_user)) {
         $user = new User($id_user);
         foreach ($site_domains as $site) {
             foreach ($site['langs'] as $l) {
                 $user->delRoles($l['root_id']);
                 $roles = $fld['sites'][$l['root_id']]['roles'];
                 if (is_array($roles) and !empty($roles)) {
                     foreach ($fld['sites'][$l['root_id']]['roles'] as $role_id => $role) {
                         $user->addRole($role_id, $l['root_id']);
                     }
                 }
             }
         }
     }
     return $fld;
 }
Example #3
0
 public function run()
 {
     DB::table('users')->truncate();
     DB::table('roles')->truncate();
     DB::table('users_roles')->truncate();
     $role = new Role();
     $role->name = 'admin';
     $role->save();
     $role = new Role();
     $role->name = 'user';
     $role->save();
     $user_adm = new User();
     $user_adm->username = 'admin';
     $user_adm->password = Hash::make('admin123');
     $user_adm->email = 'admin@admin.com';
     $user_adm->save();
     $user_adm->addRole('admin');
     $user_user = new User();
     $user_user->username = 'user';
     $user_user->password = Hash::make('user123');
     $user_user->email = 'user@user.com';
     $user_user->save();
     $user_user->addRole('user');
 }
     }
     $mitarbeiter->Name = $sanitizer->text($input->post->mitarbeitername);
     // Populate a field
     $mitarbeiter->Vorname = $sanitizer->text($input->post->mitarbeitervorname);
     // Populate a field
     $mitarbeiter->Strasse = $sanitizer->text($input->post->mitarbeiterstrasse);
     // Populate a field
     $mitarbeiter->Plz = $sanitizer->text($input->post->mitarbeiterplz);
     // Populate a field
     $mitarbeiter->Ort = $sanitizer->text($input->post->mitarbeiterort);
     // Populate a field
     $mitarbeiter->Telefon = $sanitizer->text($input->post->mitarbeitertelefon);
     // Populate a field
     $roles = $input->post->mitarbeiterrolle;
     foreach ($roles as $role) {
         $mitarbeiter->addRole($sanitizer->text($role));
     }
     $mitarbeiter->save();
     // remove all tmp files uploaded
     foreach ($files as $filename) {
         unlink($upload_path . $filename);
     }
 } else {
     // remove files
     foreach ($files as $filename) {
         unlink($upload_path . $filename);
     }
     // get the errors
     foreach ($u->getErrors() as $error) {
         $message .= "<p class='error'>{$error}</p>";
     }
Example #5
0
File: api.php Project: manviny/EC2
/**
 * 
 */
function registerUser($name, $email, $email2, $password, $password2)
{
    $message = "";
    /**
     * Check for spam and last 2 lines to the code
     */
    // SPAM
    if (trim($email2) != '') {
        return json_encode(["message" => "spam"]);
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return json_encode(["message" => "El email no es valido"]);
    }
    // el email existe, no se puede volver a registrar
    if (wire('users')->get("email={$email}")->id) {
        return json_encode(["message" => "El usuario ya existe"]);
    }
    // el nombre de usuario esta ocupado, su usuario será el email sanitized
    if (wire('users')->get("name={$name}")->id) {
        $name = wire('sanitizer')->email($email);
    }
    // no tiene pass -> genera uno al azar
    if ($password == "") {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%^&*()_-=+;:,.?";
        $password = substr(str_shuffle($chars), 0, 8);
        $password2 = $password;
    }
    // las constraseña no coinciden
    if ($password != $password2) {
        return json_encode(["message" => "Las contrasenas no coinciden"]);
    }
    $pass = $password;
    $u = new User();
    $u->name = wire('sanitizer')->username($name);
    $u->email = wire('sanitizer')->email($email);
    $u->pass = $pass;
    $u->addRole("guest");
    // $u->addRole("registrado");
    $u->language = wire('languages')->get("default");
    $u->save();
    return json_encode(["name" => $u->name, "password" => $u->pass, "message" => $message]);
}
Example #6
0

include "../../src/Bouncer.class.php";
include "../Shared Classes/User.class.php";
$bouncer = new Bouncer();
// Add a role     Name,      Array of pages role provides
$bouncer->addRole("Public", array("index.php", "about.php"));
// Add a role          Name,              Array of pages role provides
$bouncer->addRole("Registered User", array("myaccount.php", "editaccount.php", "viewusers.php"));
// Add a role          Name,   Array of pages role provides       List of pages that are overridden by other pages
$bouncer->addRole("Admin", array("stats.php", "manageusers.php"), array("viewusers.php" => "manageusers.php"));
// Here we add some users. The user class here extends the BouncerUser class, so it can still do whatever you
// would normally create a user class to do..
$user1 = new User();
$user2 = new User();
$user3 = new User();
$user1->addRole("Public");
$user2->addRole("Registered User");
$user3->addRole("Admin");
$bouncer->verifyAccess($user1->getRoles(), "index.php");
// True!
$bouncer->verifyAccess($user1->getRoles(), "viewusers.php");
// False! User 1 does not have access to this page.
$bouncer->verifyAccess($user2->getRoles(), "index.php");
// True!
$bouncer->verifyAccess($user2->getRoles(), "viewusers.php");
// True!
$bouncer->verifyAccess($user3->getRoles(), "index.php");
// True!
$bouncer->verifyAccess($user3->getRoles(), "viewusers.php");
// False! As an Admin, viewusers.php has been replaced
// with manageusers.php
 protected function adminAccountSave($wire)
 {
     if (!$wire->input->post->username || !$wire->input->post->userpass) {
         $this->err("Missing account information");
         return $this->adminAccount();
     }
     $superuser = $wire->roles->get("superuser");
     $user = new User();
     $user->name = $wire->input->post->username;
     $user->pass = $wire->input->post->userpass;
     $pass = $user->pass;
     if ($user->name != $wire->input->post->username || $user->pass != $wire->input->post->userpass) {
         $this->err("Your username or password contained characters that aren't accepted at this time. Please try another.");
         return $this->adminAccount();
     }
     $user->addRole($superuser);
     try {
         $wire->users->save($user);
     } catch (Exception $e) {
         $this->err("Error: " . $e->getMessage());
         return $this->adminAccount();
     }
     echo "<h2>5. Admin Account Saved</h2>";
     $this->li("User account saved. Please make note of this login information, as you will not be able to retrieve it again:");
     $this->li("Username: <strong>{$user->name}</strong>");
     $this->li("Password: <strong>{$pass}</strong>");
     echo "\n<h2>6. Complete &amp; Secure Your Installation</h2>";
     $this->li("Now that the installer is complete, it is highly recommended that you make ./site/config.php non-writable! This is important for security.");
     if (@unlink("./install.php")) {
         $this->li("Deleted this installer (./install.php) for security.");
     } else {
         $this->li("Please delete this installer. The file is located in your web root at: ./install.php");
     }
     $this->li("There are additional configuration options available in this file that you may want to review: ./site/config.php");
     $this->li("To save space, you may delete this directory (and everything in it): ./site/install/ - it's no longer needed");
     echo "\n<h2>7. Use The Site!</h2>";
     echo "<p><a target='_blank' href='./'>View the Web Site</a> or <a href='./processwire/'>Login to ProcessWire</a></p>";
     // set a define that indicates installation is completed so that this script no longer runs
     file_put_contents("./site/assets/installed.php", "<?php // The existance of this file prevents the installer from running. Don't delete it unless you want to re-run the install or you have deleted ./install.php.");
 }
Example #8
0
 $password = $input->post->password;
 if (strlen($username) != 0) {
     if (username_validation($username) == 0) {
         //if (1==2) {
         //$username->error = " ";
         $err_count++;
         $errors[] = "That email address is already in use!";
     }
 }
 if (!$err_count) {
     $new_user = new User();
     $new_user->of(false);
     $new_user->name = $username;
     $new_user->email = $email;
     $new_user->pass = $password;
     $new_user->addRole("guest");
     $new_user->firstname = $firstname;
     $new_user->lastname = $lastname;
     //$new_user->user_activation = $activation;
     $new_user->save();
     $new_user->of(true);
 }
 if (!$err_count) {
     $response_array['status'] = 1;
 } else {
     $response_array['status'] = 0;
     foreach ($errors as $error) {
         $error_str .= $error . ' ';
     }
     $response_array['error_str'] = $error_str;
 }
Example #9
0
 */
include "../../src/Bouncer.class.php";
include "../Shared Classes/User.class.php";
$bouncer = new Bouncer();
// Add a role     Name,      Array of pages role provides
$bouncer->addRole("Public", array("index.php", "about.php", "fail.php"));
// Add a role          Name,              Array of pages role provides
$bouncer->addRole("Registered User", array("myaccount.php", "editaccount.php", "viewusers.php"));
// Add a role          Name,   Array of pages role provides       List of pages that are overridden by other pages
$bouncer->addRole("Admin", array("stats.php", "manageusers.php"), array("viewusers.php" => "manageusers.php"));
// Here we add some users. The user class here extends the BouncerUser class, so it can still do whatever you
// would normally create a user class to do..
$publicUser = new User();
$registeredUser = new User();
$adminUser = new User();
$registeredAndAdmin = new User();
$publicUser->addRole("Public");
$registeredUser->addRole("Public");
// We add the public group to all users since they need it to see index.php
$registeredUser->addRole("Registered User");
$adminUser->addRole("Public");
// We add the public group to all users since they need it to see index.php
$adminUser->addRole("Admin");
$registeredAndAdmin->addRole("Public");
// We add the public group to all users since they need it to see index.php
$registeredAndAdmin->addRole("Registered User");
$registeredAndAdmin->addRole("Admin");
//$bouncer->manageAccess($publicUser->getRoles(), substr($_SERVER["PHP_SELF"], 1), "fail.php");
//$bouncer->manageAccess($registeredUser->getRoles(), substr($_SERVER["PHP_SELF"], 1), "fail.php");
//$bouncer->manageAccess($adminUser->getRoles(), substr($_SERVER["PHP_SELF"], 1), "fail.php");
$bouncer->manageAccess($registeredAndAdmin->getRoles(), substr($_SERVER["PHP_SELF"], 1), "fail.php");
 public function addUserAction(Request $request, $id)
 {
     $em = $this->getDoctrine()->getManager();
     $node = $this->getDoctrine()->getRepository('PassVaultPassBundle:Node')->find($id);
     $this->denyAccessUnlessGranted('ROLE_ADMINISTRATOR', $node);
     $email = $request->get('email');
     $user = $this->getDoctrine()->getRepository('PassVaultUserBundle:User')->findOneBy(array('email' => $email));
     if (is_null($user)) {
         $user = new User();
         $user->setEmail($email);
         $user->addRole('ROLE_USER');
         $user->setPlainPassword(md5($email));
         $em->persist($user);
     }
     $nodeuser = new NodeUser();
     $nodeuser->setNode($node);
     $nodeuser->setUser($user);
     $nodeuser->setRole($request->get('role'));
     $em->persist($nodeuser);
     $em->flush();
     return $this->redirectToRoute('passvault_node_view', array('id' => $id));
 }
Example #11
0
 /**
  * Retrieve users from the server.
  *
  * Result will always be an array of zero or more User objects.
  *
  * @param string $searchTerm - part of user name you would like to search for	 *
  * @return Array<User>
  * @throws Exception if HTTP request fails
  */
 public function getUsers($searchTerm = null)
 {
     $url = $this->restUrl . USER_BASE_URL . '/' . $searchTerm;
     $result = array();
     if ($data = $this->prepAndSend($url, array(200), 'GET', null, true)) {
         $xml = new \SimpleXMLElement($data);
     }
     foreach ($xml->user as $user) {
         $tempUser = new User($user->username, $user->password, $user->emailAddress, $user->fullName, $user->tenantId, $user->enabled, $user->externallyDefined, $user->previousPasswordChangeTime);
         foreach ($user->roles as $role) {
             $tempUser->addRole(JasperClient::roleToRoleObj($role));
         }
         $result[] = $tempUser;
     }
     return $result;
 }
Example #12
0
 public function socialLogin($action = "")
 {
     if ($action == "auth") {
         // process authentication
         try {
             Hybrid_Endpoint::process();
         } catch (Exception $e) {
             // redirect back to http://URL/social/
             return Redirect::route('hybridauth');
         }
         return;
     }
     try {
         // create a HybridAuth object
         $socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php');
         if ($action == 'google') {
             $provider = $socialAuth->authenticate("Google");
         } else {
             if ($action == 'facebook') {
                 $provider = $socialAuth->authenticate("facebook");
             }
         }
         // fetch user profile
         $userProfile = $provider->getUserProfile();
         // logout
         $provider->logout();
     } catch (Exception $e) {
         // exception codes can be found on HybBridAuth's web site
         return $e->getMessage();
     }
     //check user to login or create new
     $user = User::where('email', $userProfile->email)->first();
     if (isset($user->email)) {
         //can update user and login
         $user->lastest_login = date("Y-m-d H:i:s");
         if ($action == 'facebook' && empty($user->facebook_id)) {
             $user->facebook_id = $userProfile->identifier;
             $user->save();
         } elseif ($action == 'google' && empty($user->google_id)) {
             $user->google_id = $userProfile->identifier;
             $user->save();
         }
         //return Redirect::to('/login')->with('notice',Lang::get('user_texts.social_is_exist'));
         if (!empty($user->authy)) {
             $authcontroller = new AuthController();
             $auth_controller = $authcontroller->getAuthy();
             $requestSms = $auth_controller->requestSms($user->authy);
             // echo "<pre>errors: "; print_r($requestSms->errors()); echo "</pre>";
             // echo "<pre>requestSms: "; print_r($requestSms); echo "</pre>";
             if ($requestSms->ok()) {
                 //$notices =  $requestSms->ok(); //return true
                 return Redirect::to('sms-verify')->with('authy_id', $user->authy)->with('user_login', $user->id);
             } else {
                 //not_sent_token
                 $errors = $requestSms->errors();
                 return Redirect::to('login')->with('error', $errors->message);
             }
         } else {
             Auth::login($user);
             return Redirect::to('/');
         }
     } else {
         //create new user and login
         $user = new User();
         $user->firstname = $userProfile->firstName;
         $user->lastname = $userProfile->lastName;
         $user->email = $userProfile->email;
         $user->username = $userProfile->identifier;
         $user->password = $userProfile->identifier;
         $user->password_confirmation = $userProfile->identifier;
         $user->banned = 0;
         $user->confirmed = 1;
         $user->referral = '';
         $trade_key = md5($user->username . $user->email . time());
         $user->trade_key = $trade_key;
         $user->ip_lastlogin = $this->get_client_ip();
         $user->lastest_login = date("Y-m-d H:i:s");
         if ($action == 'facebook' && empty($user->facebook_id)) {
             $user->facebook_id = $userProfile->identifier;
         } elseif ($action == 'google' && empty($user->google_id)) {
             $user->google_id = $userProfile->identifier;
         }
         $user->save();
         // echo "<pre>user2" . print_r( $user->email, true ) . "</pre><br />";
         if ($user->id) {
             $user->addRole('User');
             $input = array('email' => $userProfile->email, 'username' => $userProfile->email, 'password' => $userProfile->identifier, 'remember' => 0);
             //login
             if ($c = Confide::logAttempt($input, Config::get('confide::signup_confirm'))) {
                 return Redirect::to('/');
             } else {
                 $user = new User();
                 // Check if there was too many login attempts
                 if (Confide::isThrottled($input)) {
                     $err_msg = Lang::get('confide::confide.alerts.too_many_attempts');
                 } elseif ($user->checkUserExists($input) and !$user->isConfirmed($input)) {
                     $err_msg = Lang::get('confide::confide.alerts.not_confirmed');
                 } else {
                     $err_msg = Lang::get('confide::confide.alerts.wrong_credentials');
                 }
                 return Redirect::action('UserController@login')->with('error', $err_msg);
             }
         } else {
             $error = $user->errors()->all(':message');
             return Redirect::to('user/register')->withInput(Input::except('password'))->with('error', $error);
         }
     }
 }
Example #13
0
 public static function createUser()
 {
     $timecode = substr(md5(microtime()), 0, 5);
     $role = new Role('ROLE_USER', null, 'false');
     $result = new User();
     $result->setUsername('test_' . $timecode);
     $result->setPassword($timecode);
     $result->setEmailAddress('test@' . $timecode . '.com');
     $result->setFullname('User ' . $timecode);
     $result->setTenantId('organization_1');
     $result->setEnabled('true');
     $result->addRole($role);
     return $result;
 }
 public function addNewUser()
 {
     $user = new User();
     $user->firstname = Input::get('firstname');
     $user->lastname = Input::get('lastname');
     $user->username = Input::get('username');
     $user->email = Input::get('email');
     $user->password = Input::get('password');
     $user->banned = 0;
     $user->confirmed = 1;
     $roles = Input::get('roles');
     //echo "<pre>roles"; print_r($roles); echo "</pre>"; exit;
     // The password confirmation will be removed from model
     // before saving. This field will be used in Ardent's
     // auto validation.
     $user->password_confirmation = Input::get('password_confirmation');
     $user_email = User::where('email', $user->email)->first();
     if (isset($user_email->id)) {
         return Redirect::to('admin/manage/users')->with('error', Lang::get('admin_messages.email_exist'));
     }
     $user_username = User::where('username', $user->username)->first();
     if (isset($user_username->id)) {
         return Redirect::to('admin/manage/users')->with('error', Lang::get('admin_messages.username_exist'));
     }
     // Save if valid. Password field will be hashed before save
     $user->save();
     if ($user->id) {
         if ($roles) {
             foreach ($roles as $role) {
                 $user->addRole($role);
             }
         } else {
             $user->addRole('User');
         }
         $notice = Lang::get('confide::confide.alerts.account_created');
         // Redirect with success message, You may replace "Lang::get(..." for your custom message.
         return Redirect::to('admin/manage/users')->with('success', $notice);
     } else {
         // Get validation errors (see Ardent package)
         $error = $user->errors()->all(':message');
         return Redirect::to('admin/manage/users')->withInput(Input::except('password'))->with('error', $error);
     }
 }