function insertUser($userArray) { $currTimestamp = time(); $crypt = new Crypt(); $salt = $crypt->generateSalt(); $encPass = $crypt->crypt($userArray["password"], $salt); $this->db->exec("INSERT INTO users (name,surname,email,salt,password,active,is_admin,created_on) VALUES (:name,:surname,:email,:salt,:password,:active,:is_admin,:created_on)", array(':name' => $userArray["name"], ':surname' => $userArray["surname"], ':email' => $userArray["email"], ':salt' => $salt, ':password' => $encPass, ':active' => 1, ':is_admin' => 1, ':created_on' => time())); }
/** * Tests Crypt->decrypt() */ public function testDecrypt() { // Encrypt the data $encrypted = $this->crypt->encrypt(self::DATA); // Decrypt the data $decrypted = $this->crypt->decrypt($encrypted); $this->assertTrue($decrypted == self::DATA, 'Testing data decryption'); unset($encrypted, $decrypted); }
private static function decrypt($encrypted) { if (!class_exists('Crypt')) { require dirname(__FILE__) . '/crypt.class.php'; } $cypher = new Crypt(Crypt::CRYPT_MODE_HEXADECIMAL, Crypt::CRYPT_HASH_SHA1); $cypher->Key = AUTH_KEY; return $cypher->decrypt($encrypted); }
public function testAll() { $text = 'this is my plain text'; $key = 'this is the password'; $c = new Crypt(); $cipher = $c->encrypt($key, $text); $plain = $c->decrypt($key, $cipher); $this->assertSame($text, $plain); }
public static function write($session_id, $data) { // encryption $crypt = new Crypt(); $data = $crypt->encrypt($data); $sessions = new Sessions(); $sessions->session_id = $session_id; $sessions->data = $data; $s = $sessions->where("session_id = ?", $session_id)->find(); if (is_null($s)) { return $sessions->save(); } $sessions->id = $s->id; return $sessions->update(); }
public function dologin() { $params = Input::all(); if (empty($params['username'])) { Session::flash('error', '用户名必须填写'); return Redirect::route('login'); } if (empty($params['password'])) { Session::flash('error', '密码必须填写'); return Redirect::route('login'); } if (empty($params['captcha'])) { Session::flash('error', '验证码必须填写'); return Redirect::route('login'); } if (!$this->_validate_captcha($params['captcha'])) { Session::flash('error', '验证码错误'); return Redirect::route('login'); } $password = md5(md5($params['password'])); $admin = AdminORM::whereUsername($params['username'])->wherePwd($password)->where('status', '<>', BaseORM::DISABLE)->first(); if (!empty($admin)) { Session::flash('success', '登陆成功'); $admin_id_cookie = Cookie::forever('admin_id', $admin->id); $admin_username_cookie = Cookie::forever('admin_username', $admin->username); $k_cookie = Cookie::forever('k', Crypt::encrypt($admin->id . $admin->username)); $login_time_cookie = Cookie::forever('login_time', time()); $admin->last_login_time = date('Y-m-d H:i:s'); $admin->save(); return Redirect::route('home')->withCookie($k_cookie)->withCookie($admin_id_cookie)->withCookie($admin_username_cookie)->withCookie($login_time_cookie); } else { Session::flash('error', '用户没找到'); return Redirect::route('login'); } }
private static function data() { $title = Http::getParam('title'); $content = Http::getParam('content'); $title = Crypt::EnCrypt($title, uniqid()); Article::putArticle(self::getIndex(), json_encode(array('title' => $title, 'content' => Crypt::EnCrypt($content, uniqid())))); }
/** * Store a newly created resource in storage. * * @param Request $request * @return Response */ public function store(Requests\SignUpRequest $request) { // $usermodel = new User(); $all = $request->all(); try { $password = $all["password"]; $payload = \Crypt::encrypt($password); $all["password"] = $payload; $all['role'] = 5; if (isset($all['_token'])) { unset($all['_token']); } $user = $usermodel->newUser($all); if ($user) { $login = $this->login($all); return $login; } dd("signup failed!"); } catch (Exception $e) { $message = $e->getMessage(); $code = $e->getCode(); dd(["message" => $message, "code" => $code]); } }
/** * Reverse the migrations. * * @return void */ public function down() { $gateways = DB::table('account_gateways')->get(['id', 'config']); foreach ($gateways as $gateway) { DB::table('account_gateways')->where('id', $gateway->id)->update(['config' => Crypt::decrypt($gateway->config)]); } }
public static function getHomeOverview() { $db = Auth::user()->targets()->where('closed', '=', 0)->orderBy('duedate', 'DESC')->get(); $ids = array(); $data = array(); foreach ($db as $t) { $ids[] = intval($t->id); $tr = array('id' => $t->id, 'description' => Crypt::decrypt($t->description), 'amount' => floatval($t->amount), 'duedate' => $t->duedate != '0000-00-00' ? new DateTime($t->duedate) : null, 'startdate' => $t->startdate != '0000-00-00' ? new DateTime($t->startdate) : null, 'account' => intval($t->account_id), 'saved' => 0); $tr['pct'] = round($tr['saved'] / $tr['amount'] * 100, 2); $data[intval($t->id)] = $tr; } if (count($ids) > 0) { $transfers = Auth::user()->transfers()->whereIn('target_id', $ids)->where('date', '<=', Session::get('period')->format('Y-m-d'))->get(); foreach ($transfers as $t) { if ($t->account_from == $data[$t->target_id]['account']) { $data[intval($t->target_id)]['saved'] -= floatval($t->amount); } else { if ($t->account_to == $data[$t->target_id]['account']) { $data[intval($t->target_id)]['saved'] += floatval($t->amount); } } } } return $data; }
public function index() { $encryptedkey = Crypt::encrypt("joomla"); Config::set('session.driver', 'native'); Session::put('api_key', $encryptedkey); return Response::json(array('status' => 'OK', '_token' => $encryptedkey)); }
public function run() { $data = $this->_context->get("data", ''); // Log::Write('【加密数据】Remote Accept:' . $data, Log::DEBUG); if ($this->_context->isPOST()) { $de_data = Crypt::decrypt($data, App::getConfig('YUC_SECURE_KEY')); // Log::Write('解析的加密数据:' . $de_data, Log::DEBUG); $post = json_decode($de_data, TRUE); if ($post != '' && is_array($post) && $post['site_key'] == md5(App::getConfig('YUC_SITE_KEY'))) { $mod = $post['mod']; $act = $post['act']; $class = 'Remote_' . $mod; if ($act == 'show' && $mod == 'Logs') { $name = $post['name']; $obj = new $class(); //self::$_string[' $name']=$name; $ret = $obj->{$act}($name); } else { $obj = new $class(); $ret = $obj->{$act}(); } Log::Write('Remote Run:' . $mod . ',' . $act . ',' . $ret, Log::DEBUG); _returnCryptAjax($ret); } else { Log::Write('安全认证错误!', Log::DEBUG); _returnCryptAjax(array('result' => 0, 'content' => '安全认证比对错误错误!')); } } else { Log::Write('远程控制错误!数据并非POST交互!', Log::DEBUG); _returnCryptAjax(array('result' => 0, 'content' => '远程控制错误!数据并非POST交互!')); } }
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { switch ($this->method()) { // Create case 'POST': // rules $rules['group_name'] = "required|unique:groups,name"; $rules['slug_name'] = "required|unique:groups,slug"; if (!count($this->permissions)) { //if permission count equal zero $rules['permissions'] = "required"; } return $rules; break; // Update // Update case 'PUT': // rules $rules['group_name'] = 'required|unique:groups,name,' . \Crypt::decrypt($this->get('id')); $rules['slug_name'] = 'required|unique:groups,slug,' . \Crypt::decrypt($this->get('id')); if (!count($this->permissions)) { //if permission count equal zero $rules['permissions'] = "required"; } return $rules; break; } }
public function getModificar($id) { $usuario = Usuario::find($id); $roles = Rol::all(); $contrasenia = Crypt::decrypt($usuario->contrasenia); return View::make("usuarios.modificar")->with("usuario", $usuario)->with("roles", $roles)->with("contrasenia", $contrasenia); }
public function saveUserInfo() { if (!isset($_SESSION)) { session_start(); } $code = \Input::get('code'); $lti = \Input::get('lti'); $instanceFromDB = LtiConfigurations::find($lti); $clientId = $instanceFromDB['DeveloperId']; $developerSecret = $instanceFromDB['DeveloperSecret']; $opts = array('http' => array('method' => 'POST')); $context = stream_context_create($opts); $url = "https://{$_SESSION['domain']}/login/oauth2/token?client_id={$clientId}&client_secret={$developerSecret}&code={$code}"; $userTokenJSON = file_get_contents($url, false, $context, -1, 40000); $userToken = json_decode($userTokenJSON); $actualToken = $userToken->access_token; $encryptedToken = \Crypt::encrypt($actualToken); $_SESSION['userToken'] = $encryptedToken; //store encrypted token in the database $courseId = $_SESSION['courseID']; $userId = $_SESSION['userID']; //make sure we have the user stored in the user table and in the userCourse table. $roots = new Roots(); //when we get the user from the LMS it gets stored in the DB. $roots->getUser($userId); $dbHelper = new DbHelper(); $role = $dbHelper->getRole('Approver'); $userCourse = UserCourse::firstOrNew(array('user_id' => $userId, 'course_id' => $courseId)); $userCourse->user_id = $userId; $userCourse->course_id = $courseId; $userCourse->role = $role->id; $userCourse->encrypted_token = $encryptedToken; $userCourse->save(); echo "App has been approved. Please reload this page"; }
public function login(Request $request) { // dd(\Crypt::encrypt('*****@*****.**')); try { $email = \Crypt::decrypt($request->get('token')); } catch (\Exception $e) { return abort('403', 'Forbidden'); } $user = User::whereEmail($email)->first(); if (!$user) { return abort('403', 'Forbidden'); } if (!$user->account) { $b2bCompany = \DB::connection('mysql-b2b')->table('companies')->where('user_id', '=', $user->id)->first(); // $b2bCompany = false; $accountName = $b2bCompany ? $b2bCompany->company_name : $user->email; $account = new Account(); $account->ip = $request->getClientIp(); $account->name = $accountName; $account->account_key = str_random(RANDOM_KEY_LENGTH); $account->save(); $user->account_id = $account->id; $user->registered = true; $user->save(); $exists = \DB::connection('mysql')->table('users')->whereId($user->id)->count(); if (!$exists) { \DB::connection('mysql')->table('users')->insert(['id' => $user->id, 'account_id' => $user->account_id, 'created_at' => $user->created_at, 'updated_at' => $user->updated_at, 'deleted_at' => $user->deleted_at, 'first_name' => $user->first_name, 'last_name' => $user->last_name, 'phone' => $user->phone, 'username' => $user->username, 'email' => $user->email, 'password' => $user->password, 'confirmation_code' => $user->confirmation_code, 'registered' => $user->registered, 'confirmed' => $user->confirmed, 'notify_sent' => $user->notify_sent, 'notify_viewed' => $user->notify_viewed, 'notify_paid' => $user->notify_paid, 'public_id' => $user->public_id, 'force_pdfjs' => false, 'remember_token' => $user->remember_token, 'news_feed_id' => $user->news_feed_id, 'notify_approved' => $user->notify_approved, 'failed_logins' => $user->failed_logins, 'dark_mode' => $user->dark_mode, 'referral_code' => $user->referral_code]); } } \Auth::loginUsingId($user->id); return redirect('/'); }
/** * Authenticates a user to LDAP * * @param $username * @param $password * @param bool|false $returnUser * @return bool true if the username and/or password provided are valid * false if the username and/or password provided are invalid * array of ldap_attributes if $returnUser is true */ function ldap($username, $password, $returnUser = false) { $ldaphost = Setting::getSettings()->ldap_server; $ldaprdn = Setting::getSettings()->ldap_uname; $ldappass = Crypt::decrypt(Setting::getSettings()->ldap_pword); $baseDn = Setting::getSettings()->ldap_basedn; $filterQuery = Setting::getSettings()->ldap_auth_filter_query . $username; $ldapversion = Setting::getSettings()->ldap_version; // Connecting to LDAP $connection = ldap_connect($ldaphost) or die("Could not connect to {$ldaphost}"); // Needed for AD ldap_set_option($connection, LDAP_OPT_REFERRALS, 0); ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, $ldapversion); try { if ($connection) { // binding to ldap server $ldapbind = ldap_bind($connection, $ldaprdn, $ldappass); if (($results = @ldap_search($connection, $baseDn, $filterQuery)) != false) { $entry = ldap_first_entry($connection, $results); if (($userDn = @ldap_get_dn($connection, $entry)) !== false) { if (($isBound = ldap_bind($connection, $userDn, $password)) == "true") { return $returnUser ? array_change_key_case(ldap_get_attributes($connection, $entry), CASE_LOWER) : true; } } } } } catch (Exception $e) { LOG::error($e->getMessage()); } ldap_close($connection); return false; }
public function contacto() { $mensaje = null; $userpass = User::where('email', '=', Input::get('email'))->first(); if ($userpass) { $pass = Crypt::decrypt($userpass->encry); $nombre = $userpass->username; if (isset($_POST['contacto'])) { $data = array('nombre' => $nombre, 'email' => Input::get('email'), 'pass' => $pass); $fromEmail = Input::get('email'); $fromName = Input::get('nombre'); Mail::send('emails.contacto', $data, function ($message) use($fromName, $fromEmail) { $message->to($fromEmail, $fromName); $message->from('*****@*****.**', 'administrador'); $message->subject('Nuevo Email de contacto'); }); } return Redirect::to('email')->with('status', 'ok_send'); } else { return Redirect::to('email')->with('status', 'not_send'); } //$data = Input::get('nombre'); /*foreach ($data as $key => $value) { echo $value.'<br>'; }*/ //echo $data; //var_dump($data); //return View::make('password.remind')->with('status', 'ok_create'); }
/** * Bootstrap any application services. * * @return void */ public function boot() { if ($locale = request()->cookie('locale__myProject')) { app()->setLocale(\Crypt::decrypt($locale)); } \Carbon\Carbon::setLocale(app()->getLocale()); }
/** * Updates a gateway. * * @param Model_Gateway $gateway The gateway to update. * @param array $data The data to use to update the gateway. * * @return Model_Gateway */ public static function update(Model_Gateway $gateway, array $data = array()) { $gateway->populate($data); if (!empty($data['meta'])) { $meta_names = array_keys($data['meta']); $gateway_metas = $gateway->meta($meta_names); $enc_key = Config::get('security.db_enc_key'); foreach ($meta_names as $name) { $value = Crypt::encode($data['meta'][$name], $enc_key); if (!isset($gateway_metas[$name])) { $name_meta = Model_Gateway_Meta::name($name, $value); $gateway->metas[] = $name_meta; } else { $name_meta = $gateway_metas[$name]; $name_meta->value = $value; try { $name_meta->save(); } catch (FuelException $e) { Log::error($e); return false; } } } } try { $gateway->save(); } catch (FuelException $e) { Log::error($e); return false; } return $gateway; }
public function compare() { // get a list of all months: $months = array(); $first = BaseController::getFirst(); $first->modify('first day of this month midnight'); $today = new Carbon('now'); $today->modify('first day of this month midnight'); $prev = clone $today; $prev->sub(new DateInterval('P2D')); $prev->modify('first day of this month midnight'); while ($first <= $today) { $index = $first->format('Y-m-d'); $months[$index] = $first->format('F Y'); $first->add(new DateInterval('P1M')); } // account list: $accs = Auth::user()->accounts()->get(); $accounts = array(0 => '(all accounts)'); foreach ($accs as $acc) { $accounts[intval($acc->id)] = Crypt::decrypt($acc->name); } $account = Setting::getSetting('defaultCheckingAccount'); return View::make('pages.compare')->with('months', $months)->with('thisMonth', $today)->with('prevMonth', $prev)->with('account', $account)->with('accounts', $accounts); }
public function postLogin(Request $request) { $this->validate($request, ['user_id' => 'required', 'password' => 'required']); $credentials = $request->only('user_id', 'password'); $redirect = $this->redirectPath(); $lock_new_users = true; $try = false; if (User::find($credentials['user_id'])) { // The user exists $try = true; } else { if ($lock_new_users) { return redirect('/locked'); } else { if (($person = Person::find($credentials['user_id'])) && DataSource::check_login($credentials['user_id'], $credentials['password'])) { // The ID exists and details are correct, but there isn't an account for it. Make one. $user = User::create(['user_id' => $credentials['user_id'], 'name' => $person->name, 'password' => \Crypt::encrypt($credentials['password']), 'is_queued' => true]); \Queue::push(new PrepareUser($user)); $redirect = '/setup'; $try = true; } } } if ($try && Auth::attempt($credentials, $request->has('remember'))) { return redirect()->intended($redirect); } return redirect($this->loginPath())->withInput($request->only('user_id', 'remember'))->withErrors(['user_id' => $this->getFailedLoginMessage()]); }
public function save() { // Get all inputs $input = Input::all(); // Retrive the project details $project = Project::find($input['project_id']); // Assign values $project->name = $input['name']; $project->project_type = $input['project_type']; $project->description = $input['description']; $project->client_name = $input['client_name']; $project->start_at = $input['start_at']; $project->complete_at = $input['complete_at']; // Identify if this project is on hold or not if (isset($input['status'])) { $project->status = 2; } else { $project->status = 1; } // Update the project details $project->save(); // Assign each user in a project foreach (array_merge($input['developers'], $input['qc']) as $key => $value) { $user = ProjectUsers::firstOrCreate(array('project_id' => $input['project_id'], 'user_id' => $value)); $user->key = Crypt::encrypt(time()); $user->save(); } // Redirect to project page with message return Redirect::to('/project/' . $project->slug)->with('flash_msg', 'This project was successfully updated!'); }
public function saveUserInfo() { if (!isset($_SESSION)) { session_start(); } $code = \Input::get('code'); $lti = \Input::get('lti'); $instanceFromDB = LtiConfigurations::find($lti); $clientId = $instanceFromDB['DeveloperId']; $developerSecret = $instanceFromDB['DeveloperSecret']; $opts = array('http' => array('method' => 'POST')); $context = stream_context_create($opts); $url = "https://{$_SESSION['domain']}/login/oauth2/token?client_id={$clientId}&client_secret={$developerSecret}&code={$code}"; $userTokenJSON = file_get_contents($url, false, $context, -1, 40000); $userToken = json_decode($userTokenJSON); $actualToken = $userToken->access_token; $encryptedToken = \Crypt::encrypt($actualToken); $_SESSION['userToken'] = $encryptedToken; //store encrypted token in the database $courseId = $_SESSION['courseID']; $userId = $_SESSION['userID']; $user = new User(); $user->user_id = $userId; $user->course_id = $courseId; $user->encrypted_token = $encryptedToken; $user->save(); echo "App has been approved. Please reload this page"; }
private function check($d) { global $LANGUAGES; if (!Data::checkFilled($d['language'])) { Error::msg("Por favor, escolha uma linguagem.", __METHOD__); } if (!in_array($d['language'], array_keys($LANGUAGES))) { Error::msg("A linguagem '" . $d['language'] . "' não é válida", __METHOD__); } if (empty($d['source'])) { Error::msg("Por favor, preencha o campo <b>código fonte</b>.", __METHOD__); } require_once b1n_PATH_LIB . "/Crypt.lib.php"; $seccode = $d['seccode']; $seccode = Crypt::encrypt(strtolower($seccode)); if (!isset($_SESSION['seccode'])) { Error::msg("Digite o que está escrito na imagem corretamente.", __METHOD__); } if (strcmp($seccode, $_SESSION['seccode']) != 0) { Error::msg("Digite o que está escrito na imagem corretamente.", __METHOD__); } $md5 = md5($d['source']); $query = "SELECT pas_id FROM paste WHERE pas_md5 = '" . $md5 . "'"; $rs = $this->sql->singleQuery($query); if (is_array($rs) && count($rs)) { $id = base_convert($rs['pas_id'], 10, b1n_CODE_BASE); $url = b1n_URL_ID . $id; Error::msg("Já existe um código igual a esse no banco de dados.<br />\n Veja: <a href='{$url}'>{$url}</a>", __METHOD__); } return true; }
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { switch ($this->method()) { // Create case 'POST': // rules $rules['first_name'] = "required"; $rules['last_name'] = "required"; $rules['phone'] = "required|unique:users,phone"; $rules['slug_name'] = "required|unique:users,slug"; $rules['email'] = "required|email"; $rules['password'] = "******"; $rules['group'] = "required"; return $rules; break; // Update // Update case 'PUT': // rules $rules['first_name'] = "required"; $rules['last_name'] = "required"; $rules['phone'] = "required|unique:users,phone," . \Crypt::decrypt($this->get('id')); $rules['slug_name'] = 'required|unique:users,slug,' . \Crypt::decrypt($this->get('id')); $rules['email'] = "required|email"; if ($this->has('password')) { $rules['password'] = "******"; } $rules['group'] = "required"; return $rules; break; } }
/** * Vlidate access key and find user * @param string $accessKey * @return CmfDbObject|bool - false = failed to parse access key, validate data or load user */ public static function loadFromPasswordRecoveryAccessKey($accessKey) { try { $data = \Crypt::decrypt($accessKey); } catch (DecryptException $exc) { return false; } if (empty($data)) { return false; } $data = json_decode($data, true); if (empty($data) || !is_array($data) || empty($data['account_id']) || empty($data['expires_at']) || $data['expires_at'] < time()) { return false; } /** @var CmfDbObject|ResetsPasswordsViaAccessKey $user */ $user = static::create(); $conditions = [$user->_getPkFieldName() => $data['account_id']]; foreach ($user->getAdditionalFieldsForPasswordRecoveryAccessKey() as $fieldName) { if (empty($data[$fieldName])) { return false; } $conditions[$fieldName] = $data[$fieldName]; } if (!$user->find($conditions)->exists()) { return false; } return $user; }
public function postSave() { if (\Auth::user()->role != "admin") { abort(401); } $data = \Input::all(); $validator = \Validator::make($data, ['name' => 'required']); if ($validator->fails()) { // The given data did not pass validation abort(400); } if (isset($data["tsigname"]) && $data["tsigname"] != "") { $data["tsigname"] = \Crypt::encrypt($data["tsigname"]); } if (isset($data["tsigkey"]) && $data["tsigkey"] != "") { $data["tsigkey"] = \Crypt::encrypt($data["tsigkey"]); } if (\Input::has('id')) { $zone = \App\Zone::find(\Input::get("id")); $zone->update($data); } else { $zone = \App\Zone::create($data); } return $this->getAllZones(); }
public function updateBudgetPrediction($event) { $event->name = Crypt::decrypt($event->name); // remove all budget prediction points, if any $event->budgetpredictionpoints()->delete(); $similar = array(); // get all similar budgets from the past: $budgets = Auth::user()->budgets()->where('date', '<=', $event->date)->get(); foreach ($budgets as $budget) { $budget->name = Crypt::decrypt($budget->name); if ($budget->name == $event->name) { $similar[] = $budget->id; } } if (count($similar) > 0) { // get all transactions for these budgets: $amounts = array(); $transactions = Auth::user()->transactions()->orderBy('date', 'DESC')->where('onetime', '=', 0)->whereIn('budget_id', $similar)->get(); foreach ($transactions as $t) { $date = new Carbon($t->date); $day = intval($date->format('d')); $amounts[$day] = isset($amounts[$day]) ? $amounts[$day] + floatval($t->amount) * -1 : floatval($t->amount) * -1; } // then make sure it's "average". foreach ($amounts as $day => $amount) { // save as budget prediction point. $bpp = new Budgetpredictionpoint(); $bpp->budget_id = $event->id; $bpp->amount = $amount / count($similar); $bpp->day = $day; $bpp->save(); } } }
/** * Encrypt value * * @param string $key * @param mixed $value * @return $this */ public function setAttribute($key, $value) { if (in_array($key, $this->encryptable)) { return parent::setAttribute($key, \Crypt::encrypt($value)); } return parent::setAttribute($key, $value); }