/** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); $user->status = 0; if ($user->save()) { Yii::$app->getSession()->setFlash('success', ['type' => 'success', 'duration' => 5000, 'icon' => 'fa fa-users', 'message' => 'Successfully Register', 'title' => 'Hi, ' . $user->username . ' Thanks for register..', 'positonY' => 'top', 'positonX' => 'left']); $notification = new \sintret\gii\models\Notification(); $notification->title = 'user'; $notification->message = 'new user, username:'******'model' => 'User', 'id' => $user->id]); if ($notification->save()) { $this->sendEmail($this->email); } else { print_r($notification->getErrors()); exit(0); } return $user; } else { return $user->getErrors(); } } return null; }
private function _addOrUpdate($params) { if ($params['id']) { $user = User::findOne(['id' => $params['id']]); if (!$user) { return ['success' => 0, 'message' => 'No such user exist']; } } else { $user = new User(); } $user->username = $params['username']; $user->email = $params['email']; $user->phone = $params['phone']; $user->password = $params['password']; if (!$user->validate()) { return ['success' => 0, 'message' => $user->getErrors()]; } if (count($_FILES)) { $uploader = new FileUploader($_FILES['profile_picture']); $fileName = md5($user->email . Yii::$app->security->generateRandomString()); $path = Yii::$app->basePath . '/web/images/profile/' . $fileName . '.' . $uploader->extension(); $uploadStatus = $uploader->save($path); if (!$uploadStatus['success']) { return ['success' => 0, 'message' => $uploadStatus['error']]; } $user->profile_picture = $file_name . '.' . $uploader->extension(); } if (!$user->save()) { return ['success' => 0, 'message' => 'Some error occurred']; } return ['success' => 1, 'payload' => $user]; }
public function actionInit() { $model = new User(); $model->username = '******'; $model->auth_key = 'OocVKRx-iludROmUFYj4HmxNeC8v0-FG'; $model->password_hash = '$2y$13$0d3FeUDYGSyZft.3I77hV.E357FsqqAJFqaWPstWODMbdlSvxV2gC'; $model->email = '*****@*****.**'; $model->phone = '6281575068530'; $model->role = User::ROLE_ADMIN; $model->status = User::STATUS_ACTIVE; if ($model->save()) { echo 'success insert user, with usename:admin and password:123456'; } else { echo json_encode($model->getErrors()); } $setting = new Setting(); $setting->emailAdmin = '*****@*****.**'; $setting->emailSupport = '*****@*****.**'; $setting->emailOrder = '*****@*****.**'; $setting->facebook = 'https://www.facebook.com/sintret'; $setting->instagram = 'https://instagram.com/andyfitria/'; $setting->google = 'https://google.com/sintret/'; if ($setting->save()) { echo "\r\n success insert basic settings"; } else { echo json_encode($setting->getErrors()); } }
/** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); $user->status = 0; if ($user->save()) { $notification = new Notification(); $notification->title = 'user'; $notification->message = 'new user, username:'******'model' => 'User', 'id' => $user->id]); if ($notification->save()) { $this->sendEmail($this->email); } else { print_r($notification->getErrors()); exit(0); } return $user; } else { return $user->getErrors(); } } return null; }
/** * 注册 */ public function actionRegister() { $layout = Yii::$app->request->get('layout', 0); if ($layout == 1) { $this->layout = false; } else { $this->layout = 'userLayout'; } $postData = $this->getPostJSON(); if ($postData) { $model = new User(); $model->load($postData); $model->authKey = $this->getUUID(self::AUTH_PREFIX); $transtion = Yii::$app->db->beginTransaction(); try { if ($model->save()) { $userValidate = new UserValidate(); $userValidate->email = $model->email; $userValidate->userid = $model->id; if (!$userValidate->save()) { $transtion->rollBack(); $error = current($model->getErrors()); $message = current($error); return json_encode(['success' => 0, 'message' => $message]); } //$this->sendVaildateMail($model->email, 'user-validate', ['token'=>$userValidate->token]); $resultLog = OperationLog::saveLog($model->username . "注册", $model->id, OperationLog::TYPE_USER); if (!$resultLog['result']) { $transtion->rollBack(); return json_encode(['success' => 0, 'message' => $resultLog['message']]); } $transtion->commit(); return json_encode(['success' => 1, 'message' => '注册成功']); } else { $transtion->rollBack(); $error = current($model->getErrors()); $message = current($error); return json_encode(['success' => 0, 'message' => $message]); } } catch (Exception $e) { $transtion->rollBack(); return json_encode(['success' => 0, 'message' => $e->getMessage()]); } } else { return $this->render('_register'); } }
public function reg() { $user = new User(); var_dump($this->status); $user->username = $this->username; $user->email = $this->email; $user->status = $this->status; $user->setPassword($this->password); $user->generateAuthKey(); if ($user->save()) { return $user; } else { var_dump($user->getErrors()); exit; $this->addErrors($user->getErrors()); return null; } }
/** * Create user command. * * @param $email email address * @param $password plain password */ public function actionCreate($email, $password) { $user = new User(); $user->email = $email; $user->password = $password; $user->generateAuthKey(); if (!$user->save()) { $this->outputValidateErrors($user->getErrors()); } else { echo "[32mCreate new user with ID {$user->id}[0m\n"; } }
public function create() { if ($this->request->data) { $user = new User($this->request->data); if ($user->save()) { $this->message('Successfully to create User'); $this->redirect('Users::index'); } else { $this->message('Failed to create User, please check the error'); $errors = $user->getErrors(); } } return compact('user', 'errors'); }
public function register() { if (!$this->validate()) { return false; } $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->password = $this->password; $user->firstname = $this->firstname; $user->lastname = $this->lastname; if (!$user->save()) { Yii::warning($user->getErrors()); return false; } Yii::$app->user->login($user); return true; }
/** * Logs in a user using the provided username and password. * @return boolean whether the user is logged in successfully */ public function register() { if ($this->validate()) { $user = new User(); $user->setScenario(User::SCENARIO_REGISTER); $user->email = $this->email; $user->password = $this->password; $saveResult = $user->save(); if (!$saveResult) { /** * @todo: remove when you need to use this on real server */ var_dump($user->getErrors()); die; } return $saveResult; } return false; }
/** * Creates a new user. * @param string $name user name * @param string $email user email * @param string $password uncrypted password, if skipped random password will be generated. */ public function actionCreate($name, $email, $password = '') { if (empty($password)) { $random = Yii::$app->security->generateRandomString(8); } $user = new User(); $user->name = $name; $user->email = $email; $user->status = User::STATUS_ENABLED; $user->setPassword(empty($password) ? $random : $password); if ($user->save()) { $this->p('User "{name}" has been created.', ['name' => $user->name]); if (empty($password)) { $this->p('Random password "{password}" has been generated.', ['password' => $random]); } } else { $this->err('Couldn\'t create user.'); foreach ($user->getErrors() as $attribute => $error) { print reset($error) . PHP_EOL; } } }
public function testValidateModel() { $user = new User(array('fullname' => 'Mukhamad Ikhsan', 'email' => '*****@*****.**')); $this->assertFalse($user->save()); $this->assertEqual(array('password' => array('Password cannot be empty.')), $user->getErrors()); }
/** * Execute the console command. * * @return mixed */ public function fire() { $filename = $this->argument('filename'); if (!$this->option('testrun') == 'true') { $this->comment('======= Importing Assets from ' . $filename . ' ========='); } else { $this->comment('====== TEST ONLY Asset Import for ' . $filename . ' ===='); $this->comment('============== NO DATA WILL BE WRITTEN =============='); } if (!ini_get("auto_detect_line_endings")) { ini_set("auto_detect_line_endings", '1'); } $csv = Reader::createFromPath($this->argument('filename')); $csv->setNewline("\r\n"); $csv->setOffset(1); $duplicates = ''; // Loop through the records $nbInsert = $csv->each(function ($row) use($duplicates) { $status_id = 1; // Let's just map some of these entries to more user friendly words // User's name if (array_key_exists('0', $row)) { $user_name = trim($row[0]); } else { $user_name = ''; } // User's email if (array_key_exists('1', $row)) { $user_email = trim($row[1]); } else { $user_email = ''; } // User's email if (array_key_exists('2', $row)) { $user_username = trim($row[2]); } else { $user_username = ''; } // Asset Name if (array_key_exists('3', $row)) { $user_asset_asset_name = trim($row[3]); } else { $user_asset_asset_name = ''; } // Asset Category if (array_key_exists('4', $row)) { $user_asset_category = trim($row[4]); } else { $user_asset_category = ''; } // Asset Name if (array_key_exists('5', $row)) { $user_asset_name = trim($row[5]); } else { $user_asset_name = ''; } // Asset Manufacturer if (array_key_exists('6', $row)) { $user_asset_mfgr = trim($row[6]); } else { $user_asset_mfgr = ''; } // Asset model number if (array_key_exists('7', $row)) { $user_asset_modelno = trim($row[7]); } else { $user_asset_modelno = ''; } // Asset serial number if (array_key_exists('8', $row)) { $user_asset_serial = trim($row[8]); } else { $user_asset_serial = ''; } // Asset tag if (array_key_exists('9', $row)) { $user_asset_tag = trim($row[9]); } else { $user_asset_tag = ''; } // Asset location if (array_key_exists('10', $row)) { $user_asset_location = trim($row[10]); } else { $user_asset_location = ''; } // Asset notes if (array_key_exists('11', $row)) { $user_asset_notes = trim($row[11]); } else { $user_asset_notes = ''; } // Asset purchase date if (array_key_exists('12', $row)) { if ($row[12] != '') { $user_asset_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12])); } else { $user_asset_purchase_date = ''; } } else { $user_asset_purchase_date = ''; } // Asset purchase cost if (array_key_exists('13', $row)) { if ($row[13] != '') { $user_asset_purchase_cost = trim($row[13]); } else { $user_asset_purchase_cost = ''; } } else { $user_asset_purchase_cost = ''; } // Asset Company Name if (array_key_exists('14', $row)) { if ($row[14] != '') { $user_asset_company_name = trim($row[14]); } else { $user_asset_company_name = ''; } } else { $user_asset_company_name = ''; } // A number was given instead of a name if (is_numeric($user_name)) { $this->comment('User ' . $user_name . ' is not a name - assume this user already exists'); $user_username = ''; $first_name = ''; $last_name = ''; // No name was given } elseif ($user_name == '') { $this->comment('No user data provided - skipping user creation, just adding asset'); $first_name = ''; $last_name = ''; //$user_username = ''; } else { $user_email_array = User::generateFormattedNameFromFullName($this->option('email_format'), $user_name); $first_name = $user_email_array['first_name']; $last_name = $user_email_array['last_name']; if ($user_email == '') { $user_email = $user_email_array['username'] . '@' . config('app.domain'); } if ($user_username == '') { if ($this->option('username_format') == 'email') { $user_username = $user_email; } else { $user_name_array = User::generateFormattedNameFromFullName($this->option('username_format'), $user_name); $user_username = $user_name_array['username']; } } } $this->comment('Full Name: ' . $user_name); $this->comment('First Name: ' . $first_name); $this->comment('Last Name: ' . $last_name); $this->comment('Username: '******'Email: ' . $user_email); $this->comment('Category Name: ' . $user_asset_category); $this->comment('Item: ' . $user_asset_name); $this->comment('Manufacturer ID: ' . $user_asset_mfgr); $this->comment('Model No: ' . $user_asset_modelno); $this->comment('Serial No: ' . $user_asset_serial); $this->comment('Asset Tag: ' . $user_asset_tag); $this->comment('Location: ' . $user_asset_location); $this->comment('Purchase Date: ' . $user_asset_purchase_date); $this->comment('Purchase Cost: ' . $user_asset_purchase_cost); $this->comment('Notes: ' . $user_asset_notes); $this->comment('Company Name: ' . $user_asset_company_name); $this->comment('------------- Action Summary ----------------'); if ($user_username != '') { if ($user = User::MatchEmailOrUsername($user_username, $user_email)->whereNotNull('username')->first()) { $this->comment('User ' . $user_username . ' already exists'); } else { $user = new \App\Models\User(); $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); $user->first_name = $first_name; $user->last_name = $last_name; $user->username = $user_username; $user->email = $user_email; $user->permissions = '{user":1}'; $user->password = bcrypt($password); $user->activated = 1; if ($user->save()) { $this->comment('User ' . $first_name . ' created'); } else { $this->error('ERROR CREATING User ' . $first_name . ' ' . $last_name); $this->error($user->getErrors()); } } } else { $user = new User(); } // Check for the location match and create it if it doesn't exist if ($location = Location::where('name', e($user_asset_location))->first()) { $this->comment('Location ' . $user_asset_location . ' already exists'); } else { $location = new Location(); if ($user_asset_location != '') { $location->name = e($user_asset_location); $location->address = ''; $location->city = ''; $location->state = ''; $location->country = ''; $location->user_id = 1; if (!$this->option('testrun') == 'true') { if ($location->save()) { $this->comment('Location ' . $user_asset_location . ' was created'); } else { $this->error('Something went wrong! Location ' . $user_asset_location . ' was NOT created'); $this->error($location->getErrors()); } } else { $this->comment('Location ' . $user_asset_location . ' was (not) created - test run only'); } } else { $this->comment('No location given, so none created.'); } } if (e($user_asset_category) == '') { $category_name = 'Unnamed Category'; } else { $category_name = e($user_asset_category); } // Check for the category match and create it if it doesn't exist if ($category = Category::where('name', e($category_name))->where('category_type', 'asset')->first()) { $this->comment('Category ' . $category_name . ' already exists'); } else { $category = new Category(); $category->name = e($category_name); $category->category_type = 'asset'; $category->user_id = 1; if ($category->save()) { $this->comment('Category ' . $user_asset_category . ' was created'); } else { $this->error('Something went wrong! Category ' . $user_asset_category . ' was NOT created'); $this->error($category->getErrors()); } } // Check for the manufacturer match and create it if it doesn't exist if ($manufacturer = Manufacturer::where('name', e($user_asset_mfgr))->first()) { $this->comment('Manufacturer ' . $user_asset_mfgr . ' already exists'); } else { $manufacturer = new Manufacturer(); $manufacturer->name = e($user_asset_mfgr); $manufacturer->user_id = 1; if ($manufacturer->save()) { $this->comment('Manufacturer ' . $user_asset_mfgr . ' was created'); } else { $this->error('Something went wrong! Manufacturer ' . $user_asset_mfgr . ' was NOT created: ' . $manufacturer->getErrors()->first()); } } // Check for the asset model match and create it if it doesn't exist if ($asset_model = AssetModel::where('name', e($user_asset_name))->where('modelno', e($user_asset_modelno))->where('category_id', $category->id)->where('manufacturer_id', $manufacturer->id)->first()) { $this->comment('The Asset Model ' . $user_asset_name . ' with model number ' . $user_asset_modelno . ' already exists'); } else { $asset_model = new AssetModel(); $asset_model->name = e($user_asset_name); $asset_model->manufacturer_id = $manufacturer->id; $asset_model->modelno = e($user_asset_modelno); $asset_model->category_id = $category->id; $asset_model->user_id = 1; if ($asset_model->save()) { $this->comment('Asset Model ' . $user_asset_name . ' with model number ' . $user_asset_modelno . ' was created'); } else { $this->error('Something went wrong! Asset Model ' . $user_asset_name . ' was NOT created: ' . $asset_model->getErrors()->first()); } } // Check for the asset company match and create it if it doesn't exist if ($user_asset_company_name != '') { if ($company = Company::where('name', e($user_asset_company_name))->first()) { $this->comment('Company ' . $user_asset_company_name . ' already exists'); } else { $company = new Company(); $company->name = e($user_asset_company_name); if ($company->save()) { $this->comment('Company ' . $user_asset_company_name . ' was created'); } else { $this->error('Something went wrong! Company ' . $user_asset_company_name . ' was NOT created: ' . $company->getErrors()->first()); } } } else { $company = new Company(); } // Check for the asset match and create it if it doesn't exist if ($asset = Asset::where('asset_tag', e($user_asset_tag))->first()) { $this->comment('The Asset with asset tag ' . $user_asset_tag . ' already exists'); } else { $asset = new Asset(); $asset->name = e($user_asset_asset_name); if ($user_asset_purchase_date != '') { $asset->purchase_date = $user_asset_purchase_date; } else { $asset->purchase_date = null; } if ($user_asset_purchase_cost != '') { $asset->purchase_cost = ParseFloat(e($user_asset_purchase_cost)); } else { $asset->purchase_cost = 0.0; } $asset->serial = e($user_asset_serial); $asset->asset_tag = e($user_asset_tag); $asset->model_id = $asset_model->id; $asset->assigned_to = $user->id; $asset->rtd_location_id = $location->id; $asset->user_id = 1; $asset->status_id = $status_id; $asset->company_id = $company->id; if ($user_asset_purchase_date != '') { $asset->purchase_date = $user_asset_purchase_date; } else { $asset->purchase_date = null; } $asset->notes = e($user_asset_notes); if ($asset->save()) { $this->comment('Asset ' . $user_asset_name . ' with serial number ' . $user_asset_serial . ' was created'); } else { $this->error('Something went wrong! Asset ' . $user_asset_name . ' was NOT created: ' . $asset->getErrors()->first()); } } $this->comment('====================================='); return true; }); }
/** * Создание учётной записи администратора */ public function actionCreateAdmin() { $this->stdout('Добавление администратора' . PHP_EOL); $this->stdout('Логин: ' . PHP_EOL); $username = Console::stdin(); $this->stdout('E-mail: ' . PHP_EOL); $email = Console::stdin(); $this->stdout('Пароль: ' . PHP_EOL); $password = Console::stdin(); $user = new User(); $user->username = $username; $user->email = $email; $user->setPassword($password); $user->generateAuthKey(); if ($user->validate() === false) { $this->stdout('Ошибки при вводе данных: ' . print_r($user->getErrors(), true)); return; } if ($user->save()) { $this->stdout('Пользователь добавлен' . PHP_EOL, Console::FG_GREEN); /** @var ManagerInterface $auth */ $auth = Yii::$app->authManager; $authorRole = $auth->getRole(AclHelper::ROLE_ADMIN); $auth->assign($authorRole, $user->id); $this->stdout('Права пользователя добавлены' . PHP_EOL, Console::FG_GREEN); } }
/** * @return User */ private function userInit() { $user = new User(); $user->username = '******'; $user->email = '*****@*****.**'; $user->setPassword('admin'); $user->first_name = 'admin'; $user->last_name = 'admin'; $user->generateAuthKey(); if ($user->save()) { $this->rbacInit($user->id); return $user; } else { die(var_dump($user->getErrors())); } }
/** * LDAP form processing. * * @author Aladin Alaily * @since [v1.8] * @return Redirect */ public function postLDAP(Request $request) { ini_set('max_execution_time', 600); //600 seconds = 10 minutes ini_set('memory_limit', '500M'); $ldap_result_username = Setting::getSettings()->ldap_username_field; $ldap_result_last_name = Setting::getSettings()->ldap_lname_field; $ldap_result_first_name = Setting::getSettings()->ldap_fname_field; $ldap_result_active_flag = Setting::getSettings()->ldap_active_flag_field; $ldap_result_emp_num = Setting::getSettings()->ldap_emp_num; $ldap_result_email = Setting::getSettings()->ldap_email; try { $ldapconn = Ldap::connectToLdap(); } catch (\Exception $e) { return redirect()->back()->withInput()->with('error', $e->getMessage()); } try { Ldap::bindAdminToLdap($ldapconn); } catch (\Exception $e) { return redirect()->back()->withInput()->with('error', $e->getMessage()); } $summary = array(); $results = Ldap::findLdapUsers(); $tmp_pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); $pass = bcrypt($tmp_pass); for ($i = 0; $i < $results["count"]; $i++) { if (empty($ldap_result_active_flag) || $results[$i][$ldap_result_active_flag][0] == "TRUE") { $item = array(); $item["username"] = isset($results[$i][$ldap_result_username][0]) ? $results[$i][$ldap_result_username][0] : ""; $item["employee_number"] = isset($results[$i][$ldap_result_emp_num][0]) ? $results[$i][$ldap_result_emp_num][0] : ""; $item["lastname"] = isset($results[$i][$ldap_result_last_name][0]) ? $results[$i][$ldap_result_last_name][0] : ""; $item["firstname"] = isset($results[$i][$ldap_result_first_name][0]) ? $results[$i][$ldap_result_first_name][0] : ""; $item["email"] = isset($results[$i][$ldap_result_email][0]) ? $results[$i][$ldap_result_email][0] : ""; // User exists $item["createorupdate"] = 'updated'; if (!($user = User::where('username', $item["username"])->first())) { $user = new User(); $user->password = $pass; $item["createorupdate"] = 'created'; } // Create the user if they don't exist. $user->first_name = e($item["firstname"]); $user->last_name = e($item["lastname"]); $user->username = e($item["username"]); $user->email = e($item["email"]); $user->employee_num = e($item["employee_number"]); $user->activated = 1; if ($request->input('location_id') != '') { $user->location_id = e($request->input('location_id')); } $user->notes = 'Imported from LDAP'; $user->ldap_import = 1; $errors = ''; if ($user->save()) { $item["note"] = $item["createorupdate"]; $item["status"] = 'success'; } else { foreach ($user->getErrors()->getMessages() as $key => $err) { $errors .= '<li>' . $err[0]; } $item["note"] = $errors; $item["status"] = 'error'; } array_push($summary, $item); } } return redirect()->route('ldap/user')->with('success', "LDAP Import successful.")->with('summary', $summary); }
/** * postSignup. * * Handles POST requests for users signing up natively through Madison * Fires MadisonEvent::NEW_USER_SIGNUP Event * * @param void * * @return Illuminate\Http\RedirectResponse */ public function postSignup() { //Retrieve POST values $email = Input::get('email'); $password = Input::get('password'); $fname = Input::get('fname'); $lname = Input::get('lname'); //Create user token for email verification $token = str_random(); //Create new user $user = new User(); $user->email = $email; $user->password = $password; $user->fname = $fname; $user->lname = $lname; $user->token = $token; if (!$user->save()) { return Redirect::to('user/signup')->withInput()->withErrors($user->getErrors()); } Event::fire(MadisonEvent::NEW_USER_SIGNUP, $user); //Send email to user for email account verification Mail::queue('email.signup', array('token' => $token), function ($message) use($email, $fname) { $message->subject('Welcome to the Madison Community'); $message->from('*****@*****.**', 'Madison'); $message->to($email); // Recipient address }); return Redirect::to('user/login')->with('message', 'An email has been sent to your email address. Please follow the instructions in the email to confirm your email address before logging in.'); }
/** * Save the first admin user from Setup. * * @author [A. Gianotto] [<*****@*****.**>] * @since [v3.0] * @return Redirect */ public function postSaveFirstAdmin(SetupUserRequest $request) { $user = new User(); $user->first_name = $data['first_name'] = e(Input::get('first_name')); $user->last_name = e(Input::get('last_name')); $user->email = $data['email'] = e(Input::get('email')); $user->activated = 1; $permissions = array('superuser' => 1); $user->permissions = json_encode($permissions); $user->username = $data['username'] = e(Input::get('username')); $user->password = bcrypt(Input::get('password')); $data['password'] = Input::get('password'); $settings = new Setting(); $settings->site_name = e(Input::get('site_name')); $settings->alert_email = e(Input::get('email')); $settings->alerts_enabled = 1; $settings->brand = 1; $settings->locale = 'en'; $settings->default_currency = 'USD'; $settings->user_id = 1; $settings->email_domain = e(Input::get('email_domain')); $settings->email_format = e(Input::get('email_format')); if (!$user->isValid() || !$settings->isValid()) { return redirect()->back()->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors()); } else { $user->save(); $settings->save(); if (Input::get('email_creds') == '1') { Mail::send(['text' => 'emails.firstadmin'], $data, function ($m) use($data) { $m->to($data['email'], $data['first_name']); $m->subject('Your Snipe-IT credentials'); }); } return redirect()->route('setup.done'); } }
/** * Finds the user matching given data, or creates a new one if there is no match * * @author Daniel Melzter * @since 3.0 * @param $row array * @return User Model w/ matching name * @internal param string $user_username Username extracted from CSV * @internal param string $user_email Email extracted from CSV * @internal param string $first_name * @internal param string $last_name */ public function createOrFetchUser($row) { $user_name = $this->array_smart_fetch($row, "name"); $user_email = $this->array_smart_fetch($row, "email"); $user_username = $this->array_smart_fetch($row, "username"); // A number was given instead of a name if (is_numeric($user_name)) { $this->log('User ' . $user_name . ' is not a name - assume this user already exists'); $user_username = ''; $first_name = ''; $last_name = ''; // No name was given } elseif (empty($user_name)) { $this->log('No user data provided - skipping user creation, just adding asset'); $first_name = ''; $last_name = ''; //$user_username = ''; } else { $user_email_array = User::generateFormattedNameFromFullName(Setting::getSettings()->email_format, $user_name); $first_name = $user_email_array['first_name']; $last_name = $user_email_array['last_name']; if ($user_email == '') { $user_email = $user_email_array['username'] . '@' . Setting::getSettings()->email_domain; } if ($user_username == '') { if ($this->option('username_format') == 'email') { $user_username = $user_email; } else { $user_name_array = User::generateFormattedNameFromFullName(Setting::getSettings()->username_format, $user_name); $user_username = $user_name_array['username']; } } } $this->log("--- User Data ---"); $this->log('Full Name: ' . $user_name); $this->log('First Name: ' . $first_name); $this->log('Last Name: ' . $last_name); $this->log('Username: '******'Email: ' . $user_email); $this->log('--- End User Data ---'); if ($this->option('testrun')) { return new User(); } if (!empty($user_username)) { if ($user = User::MatchEmailOrUsername($user_username, $user_email)->whereNotNull('username')->first()) { $this->log('User ' . $user_username . ' already exists'); } elseif ($first_name != '' && $last_name != '' && $user_username != '') { $user = new \App\Models\User(); $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); $user->first_name = $first_name; $user->last_name = $last_name; $user->username = $user_username; $user->email = $user_email; $user->password = bcrypt($password); $user->activated = 1; if ($user->save()) { $this->log('User ' . $first_name . ' created'); } else { $this->jsonError('User "' . $first_name . '"', $user->getErrors()); } } else { $user = new User(); } } else { $user = new User(); } return $user; }
/** * Create user from LDAP attributes * * @author [A. Gianotto] [<*****@*****.**>] * @since [v3.0] * @param $ldapatttibutes * @return array|bool */ static function createUserFromLdap($ldapatttibutes) { $item = Ldap::parseAndMapLdapAttributes($ldapatttibutes); // Create user from LDAP data if (!empty($item["username"])) { $user = new User(); $user->first_name = $item["firstname"]; $user->last_name = $item["lastname"]; $user->username = $item["username"]; $user->email = $item["email"]; if (Setting::getSettings()->ldap_pw_sync == '1') { $user->password = bcrypt(Input::get("password")); } else { $pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 25); $user->password = bcrypt($pass); } $user->activated = 1; $user->ldap_import = 1; $user->notes = 'Imported on first login from LDAP'; if ($user->save()) { return true; } else { LOG::debug('Could not create user.' . $user->getErrors()); exit; } } return false; }
/** * putEdit. * * User's put request to update their profile * * @param User $user * * @return Illuminate\Http\RedirectResponse */ public function putEdit(User $user) { if (!Auth::check()) { return Response::json($this->growlMessage('Please log in to edit user profile', 'error'), 401); } elseif (Auth::user()->id != $user->id) { return Response::json($this->growlMessage('You do not have access to that profile.', 'error'), 403); } elseif ($user == null) { return Response::error('404'); } if (strlen(Input::get('password')) > 0) { $user->password = Input::get('password'); } $verify = Input::get('verify_request'); $user->email = Input::get('email'); $user->fname = Input::get('fname'); $user->lname = Input::get('lname'); $user->url = Input::get('url'); $user->phone = Input::get('phone'); $user->verify = $verify; // Don't allow oauth logins to update the user's data anymore, // since they've set values within Madison. $user->oauth_update = false; if (!$user->save()) { $messages = $user->getErrors()->toArray(); $messageArray = []; foreach ($messages as $key => $value) { //If an array of messages have been passed, push each one onto messageArray if (is_array($value)) { Log::info($value); foreach ($value as $message) { array_push($messageArray, $message); } } else { //Otherwise just push the message value array_push($messageArray, $value); } } return Response::json($this->growlMessage($messageArray, 'error'), 400); } if (isset($verify)) { $meta = new UserMeta(); $meta->meta_key = 'verify'; $meta->meta_value = 'pending'; $meta->user_id = $user->id; $meta->save(); Event::fire(MadisonEvent::VERIFY_REQUEST_USER, $user); return Response::json($this->growlMessage(['Your profile has been updated', 'Your verified status has been requested.'], 'success')); } return Response::json($this->growlMessage('Your profile has been updated.', 'success')); }
/** * Execute the console command. * * @return mixed */ public function fire() { $filename = $this->argument('filename'); if (!$this->option('testrun') == 'true') { $this->comment('======= Importing Licenses from ' . $filename . ' ========='); } else { $this->comment('====== TEST ONLY License Import for ' . $filename . ' ===='); $this->comment('============== NO DATA WILL BE WRITTEN =============='); } if (!ini_get("auto_detect_line_endings")) { ini_set("auto_detect_line_endings", '1'); } $csv = Reader::createFromPath($this->argument('filename')); $csv->setNewline("\r\n"); $csv->setOffset(1); $duplicates = ''; // Loop through the records $nbInsert = $csv->each(function ($row) use($duplicates) { $status_id = 1; // Let's just map some of these entries to more user friendly words if (array_key_exists('0', $row)) { $user_name = trim($row[0]); } else { $user_name = ''; } if (array_key_exists('1', $row)) { $user_email = trim($row[1]); } else { $user_email = ''; } if (array_key_exists('2', $row)) { $user_username = trim($row[2]); } else { $user_username = ''; } if (array_key_exists('3', $row)) { $user_license_name = trim($row[3]); } else { $user_license_name = ''; } if (array_key_exists('4', $row)) { $user_license_serial = trim($row[4]); } else { $user_license_serial = ''; } if (array_key_exists('5', $row)) { $user_licensed_to_name = trim($row[5]); } else { $user_licensed_to_name = ''; } if (array_key_exists('6', $row)) { $user_licensed_to_email = trim($row[6]); } else { $user_licensed_to_email = ''; } if (array_key_exists('7', $row)) { $user_license_seats = trim($row[7]); } else { $user_license_seats = ''; } if (array_key_exists('8', $row)) { $user_license_reassignable = trim($row[8]); if ($user_license_reassignable != '') { if (strtolower($user_license_reassignable) == 'yes' || strtolower($user_license_reassignable) == 'true' || $user_license_reassignable == '1') { $user_license_reassignable = 1; } } else { $user_license_reassignable = 0; } } else { $user_license_reassignable = 0; } if (array_key_exists('9', $row)) { $user_license_supplier = trim($row[9]); } else { $user_license_supplier = ''; } if (array_key_exists('10', $row)) { $user_license_maintained = trim($row[10]); if ($user_license_maintained != '') { if (strtolower($user_license_maintained) == 'yes' || strtolower($user_license_maintained) == 'true' || $user_license_maintained == '1') { $user_license_maintained = 1; } } else { $user_license_maintained = 0; } } else { $user_license_maintained = ''; } if (array_key_exists('11', $row)) { $user_license_notes = trim($row[11]); } else { $user_license_notes = ''; } if (array_key_exists('12', $row)) { if ($row[12] != '') { $user_license_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12])); } else { $user_license_purchase_date = ''; } } else { $user_license_purchase_date = 0; } // A number was given instead of a name if (is_numeric($user_name)) { $this->comment('User ' . $user_name . ' is not a name - assume this user already exists'); $user_username = ''; // No name was given } elseif ($user_name == '') { $this->comment('No user data provided - skipping user creation, just adding license'); $first_name = ''; $last_name = ''; $user_username = ''; } else { $name = explode(" ", $user_name); $first_name = $name[0]; $email_last_name = ''; $email_prefix = $first_name; if (!array_key_exists(1, $name)) { $last_name = ''; $email_last_name = $last_name; $email_prefix = $first_name; } else { $last_name = str_replace($first_name, '', $user_name); if ($this->option('email_format') == 'filastname') { $email_last_name .= str_replace(' ', '', $last_name); $email_prefix = $first_name[0] . $email_last_name; } elseif ($this->option('email_format') == 'firstname.lastname') { $email_last_name .= str_replace(' ', '', $last_name); $email_prefix = $first_name . '.' . $email_last_name; } elseif ($this->option('email_format') == 'firstname') { $email_last_name .= str_replace(' ', '', $last_name); $email_prefix = $first_name; } } $user_username = $email_prefix; // Generate an email based on their name if no email address is given if ($user_email == '') { if ($first_name == 'Unknown') { $status_id = 7; } $email = strtolower($email_prefix) . '@' . $this->option('domain'); $user_email = str_replace("'", '', $email); } } $this->comment('Full Name: ' . $user_name); $this->comment('First Name: ' . $first_name); $this->comment('Last Name: ' . $last_name); $this->comment('Username: '******'Email: ' . $user_email); $this->comment('License Name: ' . $user_license_name); $this->comment('Serial No: ' . $user_license_serial); $this->comment('Licensed To Name: ' . $user_licensed_to_name); $this->comment('Licensed To Email: ' . $user_licensed_to_email); $this->comment('Seats: ' . $user_license_seats); $this->comment('Reassignable: ' . $user_license_reassignable); $this->comment('Supplier: ' . $user_license_supplier); $this->comment('Maintained: ' . $user_license_maintained); $this->comment('Notes: ' . $user_license_notes); $this->comment('Purchase Date: ' . $user_license_purchase_date); $this->comment('------------- Action Summary ----------------'); if ($user_username != '') { if ($user = User::where('username', $user_username)->whereNotNull('username')->first()) { $this->comment('User ' . $user_username . ' already exists'); } else { $user = new \App\Models\User(); $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); $user->first_name = $first_name; $user->last_name = $last_name; $user->username = $user_username; $user->email = $user_email; $user->permissions = '{user":1}'; $user->password = bcrypt($password); $user->activated = 1; if ($user->save()) { $this->comment('User ' . $first_name . ' created'); } else { $this->error('ERROR CREATING User ' . $first_name . ' ' . $last_name); $this->error($user->getErrors()); } $this->comment('User ' . $first_name . ' created'); } } else { $user = new User(); $user->user_id = null; } // Check for the supplier match and create it if it doesn't exist if ($supplier = Supplier::where('name', $user_license_supplier)->first()) { $this->comment('Supplier ' . $user_license_supplier . ' already exists'); } else { $supplier = new Supplier(); $supplier->name = e($user_license_supplier); $supplier->user_id = 1; if ($supplier->save()) { $this->comment('Supplier ' . $user_license_supplier . ' was created'); } else { $this->comment('Something went wrong! Supplier ' . $user_license_supplier . ' was NOT created'); } } // Add the license $license = new License(); $license->name = e($user_license_name); if ($user_license_purchase_date != '') { $license->purchase_date = $user_license_purchase_date; } else { $license->purchase_date = null; } $license->serial = e($user_license_serial); $license->seats = e($user_license_seats); $license->supplier_id = $supplier->id; $license->user_id = 1; if ($user_license_purchase_date != '') { $license->purchase_date = $user_license_purchase_date; } else { $license->purchase_date = null; } $license->license_name = $user_licensed_to_name; $license->license_email = $user_licensed_to_email; $license->notes = e($user_license_notes); if ($license->save()) { $this->comment('License ' . $user_license_name . ' with serial number ' . $user_license_serial . ' was created'); $license_seat_created = 0; for ($x = 0; $x < $user_license_seats; $x++) { // Create the license seat entries $license_seat = new LicenseSeat(); $license_seat->license_id = $license->id; // Only assign the first seat to the user if ($x == 0) { $license_seat->assigned_to = $user->id; } else { $license_seat->assigned_to = null; } if ($license_seat->save()) { $license_seat_created++; } } if ($license_seat_created > 0) { $this->comment($license_seat_created . ' seats were created'); } else { $this->comment('Something went wrong! NO seats for ' . $user_license_name . ' were created'); } } else { $this->comment('Something went wrong! License ' . $user_license_name . ' was NOT created'); } $this->comment('====================================='); return true; }); }
/** * store a resource * @param Request $this->request http request * @param mixed $id id of the resource for updating * @return jsend jsend with newly stored source */ function store($id = null) { //////////////// // Load Data // //////////////// if ($id) { $data = Model::find($id); if (!$data) { return app()->abort(404); } } else { $data = new Model(); } /////////////////////////////////// // Assign posted data to Data // /////////////////////////////////// $data->fill($this->request->input()); /////////////////////// // EMBED IMAGES // /////////////////////// foreach ($this->request->input('images') as $x) { $images[] = new Image($x); } if (!$data->syncImages($images)) { return response()->json(JSend::fail($data->getErrors())->asArray())->setCallback($this->request->input('callback')); } /////////////////////// // EMBED AUTH // /////////////////////// foreach ($this->request->input('auths') as $x) { $auths[] = new Auth($x); } if (!$data->syncAuths($auths)) { return response()->json(JSend::fail($data->getErrors())->asArray())->setCallback($this->request->input('callback')); } /////////////////////// // EMBED ACCOUNT // /////////////////////// foreach ($this->request->input('account_connects') as $x) { $accounts[] = new AccountConnect($x); } if (!$data->syncAccountConnects($accounts)) { return response()->json(JSend::fail($data->getErrors())->asArray())->setCallback($this->request->input('callback')); } /////////// // Store // /////////// if ($data->save()) { ///////////////////// // Return Response // ///////////////////// return response()->json(JSend::success(['data' => $data->toArray()])->asArray()); } else { return response()->json(JSend::fail($data->getErrors())->asArray()); } }
/** * Create user from LDAP attributes * * @author [A. Gianotto] [<*****@*****.**>] * @since [v3.0] * @param $ldapatttibutes * @return array|bool */ static function createUserFromLdap($ldapatttibutes) { $item = Ldap::parseAndMapLdapAttributes($ldapatttibutes); // Create user from LDAP data if (!empty($item["username"])) { $user = new User(); $user->first_name = $item["firstname"]; $user->last_name = $item["lastname"]; $user->username = $item["username"]; $user->email = $item["email"]; $user->password = bcrypt(Input::get("password")); $user->activated = 1; $user->ldap_import = 1; $user->notes = 'Imported on first login from LDAP'; if ($user->save()) { return true; } else { LOG::debug('Could not create user.' . $user->getErrors()); exit; } } return false; }
/** * Импорт модераторов * Взят вордовский файл с секциями для инжененрных классов * Таблица скопирована в эксель и сохранена как csv * Ручками подправлено так, чтобы в строке были полностью данные по людям: * 1 столбец: номер * 2 столбец: Образовательная организация * 3 столбец: Фамилия * 4 столбец: Имя * 5 столбец: Отчество * 6 столбец: Должность * 7 столбец: Электронный адрес * могут быть пустые строки */ public function actionImportmed($filename, $idConference = 2) { $aConfFields = [2 => ['', 'us_description', 'us_name', 'us_name', 'us_name', 'us_description', 'us_email'], 3 => ['us_name', 'us_description', 'us_email']]; if (($hd = fopen($filename, "r")) !== false) { $aFields = $aConfFields[$idConference]; $nFields = count($aFields); $aResultData = []; $aSectionId = Yii::$app->db->createCommand('Select sec_id From ' . Section::tableName() . ' Where sec_cnf_id = ' . $idConference)->queryColumn(); $this->printStr("aSectionId: " . implode(', ', $aSectionId) . "\n\n"); $nRow = 0; while (($data = fgetcsv($hd, 2000, ";")) !== false) { $nRow++; if ($nRow == 1) { continue; } $num = count($data); if ($num < $nFields) { $this->printStr("Error fields: " . implode(', ', $data) . " num = " . $num . " [{$nRow}]\n\n"); continue; } // ************************************************************************************************* // конвертируем в UTF-8 $data = array_map(function ($s) { return iconv('CP1251', 'UTF-8', $s); }, $data); // ************************************************************************************************* // тут пропускаем строку с заголовками колонок if (strpos($data[1], 'Фамилия') !== false && strpos($data[2], 'ВУЗ') !== false) { // $this->printStr( // "Col titles: " . implode(', ', $data) . " num = ".$num." [{$nRow}]\n\n" // ); continue; } // ************************************************************************************************* // тут получаем данные по полям строки $bEmpty = true; // это останется true в полностью пустой строке $aAttr = []; for ($i = 0; $i < $num; $i++) { if (!empty($data[$i])) { $bEmpty = false; // $this->printStr( // "row [{$nRow}]: $i = " . $data[$i] . " -> {$aFields[$i]}\n\n" // ); if (!empty($aFields[$i])) { $aAttr[$aFields[$i]] = (isset($aAttr[$aFields[$i]]) ? $aAttr[$aFields[$i]] . ' ' : '') . trim($data[$i]); } } } // ************************************************************************************************* // тут пропускаем полностью пустую строку if ($bEmpty) { // $this->printStr( // "Empty row: " . implode(', ', $data) . " num = ".$num." [{$nRow}]\n\n" // ); continue; } // ************************************************************************************************* // тут пропускаем без почты if (!isset($aAttr['us_email'])) { $this->printStr("No email: " . implode(', ', $data) . " [{$nRow}]\n\n"); continue; } // $this->printStr( // "aAttr: " . print_r($aAttr, true) . " [{$nRow}]\n\n" // ); // continue; $oUser = User::find()->where(['us_email' => $aAttr['us_email']])->one(); // $this->printStr( // "Data row: " . print_r($aAttr, true) . " [{$nRow}]\n\n" // ); if ($oUser === null) { //нового заводим $oUser = new User(); $oUser->scenario = 'modregister'; $aAttr['password'] = Yii::$app->security->generateRandomString(6); $oUser->us_group = User::USER_GROUP_MODERATOR; $oUser->attributes = $aAttr; $oUser->sectionids = $aSectionId; $oUser->us_active = User::STATUS_ACTIVE; if (!$oUser->save()) { $this->printStr("Error save new user: "******" [{$nRow}]\n\n"); } else { $aResultData[] = ['us_name' => $aAttr['us_name'], 'password' => $aAttr['password'], 'us_description' => $aAttr['us_description'], 'us_email' => $aAttr['us_email'], 'section' => '']; } } else { $oldSec = $oUser->sectionids; foreach ($aSectionId as $id) { if (!in_array($id, $oldSec)) { $oldSec[] = $id; } } $oUser->sectionids = $oldSec; if (!$oUser->save()) { $this->printStr("Error save exists user: "******" [{$nRow}]\n\n"); } else { $this->printStr("New user sections: " . $oUser->us_email . ' ' . implode(', ', $oldSec) . " [{$nRow}]\n\n"); } } } fclose($hd); if (count($aResultData) > 0) { $sFile = dirname($filename) . DIRECTORY_SEPARATOR . 'users-' . time() . '.csv'; $this->printResult($aResultData, $sFile); $this->printStr("Users save: " . count($aResultData) . ", file {$sFile}\n\n"); } } else { echo "\n\nCan't open file {$filename}\n\n"; } }