/** * @param User $user * @param string $role * * @return bool */ public function attachRole(User $user, string $role) : bool { $admin = Role::where('name', 'owner')->first(); $user->attachRole($admin); $user->save(); return true; }
/** * @param string $key * * @return ImportJob */ public function findByKey(string $key) : ImportJob { $result = $this->user->importJobs()->where('key', $key)->first(['import_jobs.*']); if (is_null($result)) { return new ImportJob(); } return $result; }
/** * Firefly doesn't have anything that should be in the a cron job, except maybe this one, and it's fairly exceptional. * * If you use SendGrid like I do, you can detect bounces and thereby check if users gave an invalid address. If they did, * it's easy to block them and change their password. Optionally, you could notify yourself about it and send them a message. * * But thats something not supported right now. */ public function sendgrid() { if (strlen(env('SENDGRID_USERNAME')) > 0 && strlen(env('SENDGRID_PASSWORD')) > 0) { $set = ['blocks' => 'https://api.sendgrid.com/api/blocks.get.json', 'bounces' => 'https://api.sendgrid.com/api/bounces.get.json', 'invalids' => 'https://api.sendgrid.com/api/invalidemails.get.json']; echo '<pre>'; foreach ($set as $name => $URL) { $parameters = ['api_user' => env('SENDGRID_USERNAME'), 'api_key' => env('SENDGRID_PASSWORD'), 'date' => 1, 'days' => 7]; $fullURL = $URL . '?' . http_build_query($parameters); $data = json_decode(file_get_contents($fullURL)); /* * Loop the result, if any. */ if (is_array($data)) { echo 'Found ' . count($data) . ' entries in the SendGrid ' . $name . ' list.' . "\n"; foreach ($data as $entry) { $address = $entry->email; $user = User::where('email', $address)->where('blocked', 0)->first(); if (!is_null($user)) { echo 'Found a user: '******', who is now blocked.' . "\n"; $user->blocked = 1; $user->blocked_code = 'bounced'; $user->password = '******'; $user->save(); } else { echo 'Found no user: '******', did nothing.' . "\n"; } } } } echo 'Done!' . "\n"; } else { echo 'Please fill in SendGrid details.'; } }
/** * @param Collection $accounts * @param Carbon $start * @param Carbon $end * * @return string */ public function spentInPeriod(Collection $accounts, Carbon $start, Carbon $end) : string { /** @var HasMany $query */ $query = $this->user->transactionJournals()->expanded()->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER]); if ($end >= $start) { $query->before($end)->after($start); } if ($accounts->count() > 0) { $accountIds = $accounts->pluck('id')->toArray(); $query->leftJoin('transactions as source', function (JoinClause $join) { $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')->where('source.amount', '<', 0); }); $query->leftJoin('transactions as destination', function (JoinClause $join) { $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')->where('destination.amount', '>', 0); }); $query->whereIn('source.account_id', $accountIds); $query->whereNotIn('destination.account_id', $accountIds); $query->whereNull('source.deleted_at'); $query->whereNull('destination.deleted_at'); $query->distinct(); } // remove group by $query->getQuery()->getQuery()->groups = null; $ids = $query->get(['transaction_journals.id'])->pluck('id')->toArray(); $sum = $this->user->transactions()->whereIn('transaction_journal_id', $ids)->where('amount', '<', '0')->whereNull('transactions.deleted_at')->sum('amount'); return strval($sum); }
/** * Run the database seeds. * * @return void */ public function run() { $user = User::create(['email' => '*****@*****.**', 'password' => bcrypt('james'), 'reset' => null, 'remember_token' => null]); User::create(['email' => '*****@*****.**', 'password' => bcrypt('james'), 'reset' => null, 'remember_token' => null]); $admin = Role::where('name', 'owner')->first(); $user->attachRole($admin); // create asset accounts for user #1. TestData::createAssetAccounts($user); // create bills for user #1 TestData::createBills($user); // create some budgets for user #1 $this->createBudgets($user); // create some categories for user #1 $this->createCategories($user); // create some piggy banks for user #1 TestData::createPiggybanks($user); // create some expense accounts for user #1 $this->createExpenseAccounts($user); // create some revenue accounts for user #1 $this->createRevenueAccounts($user); // create journal + attachment: $this->createAttachments($user); // create opening balance for savings account: $this->openingBalanceSavings($user); }
/** * */ protected function createUsers() { User::create(['email' => '*****@*****.**', 'password' => bcrypt('james'), 'reset' => null, 'remember_token' => null]); $this->user = User::whereEmail('*****@*****.**')->first(); // create rights: $role = Role::find(1); $this->user->roles()->save($role); }
/** * @return Collection */ public function get() : Collection { /** @var Collection $tags */ $tags = $this->user->tags()->get(); $tags = $tags->sortBy(function (Tag $tag) { return strtolower($tag->tag); }); return $tags; }
/** * @param Bill $bill * * @return Collection */ public function getPossiblyRelatedJournals(Bill $bill) : Collection { $set = new Collection(DB::table('transactions')->where('amount', '>', 0)->where('amount', '>=', $bill->amount_min)->where('amount', '<=', $bill->amount_max)->get(['transaction_journal_id'])); $ids = $set->pluck('transaction_journal_id')->toArray(); $journals = new Collection(); if (count($ids) > 0) { $journals = $this->user->transactionJournals()->transactionTypes([TransactionType::WITHDRAWAL])->whereIn('transaction_journals.id', $ids)->get(['transaction_journals.*']); } return $journals; }
/** * @param Collection $accounts * @param array $types * @param Carbon $start * @param Carbon $end * * @return string */ private function sumInPeriodWithoutCategory(Collection $accounts, array $types, Carbon $start, Carbon $end) : string { $query = $this->user->transactionJournals()->distinct()->transactionTypes($types)->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')->leftJoin('transactions as t', function (JoinClause $join) { $join->on('t.transaction_journal_id', '=', 'transaction_journals.id')->where('amount', '<', 0); })->leftJoin('category_transaction', 't.id', '=', 'category_transaction.transaction_id')->whereNull('category_transaction_journal.id')->whereNull('category_transaction.id')->before($end)->after($start); if ($accounts->count() > 0) { $accountIds = $accounts->pluck('id')->toArray(); $query->whereIn('t.account_id', $accountIds); } $sum = strval($query->sum('t.amount')); return $sum; }
/** * @return bool */ public function resetRuleGroupOrder() : bool { $this->user->ruleGroups()->whereNotNull('deleted_at')->update(['order' => 0]); $set = $this->user->ruleGroups()->where('active', 1)->orderBy('order', 'ASC')->get(); $count = 1; /** @var RuleGroup $entry */ foreach ($set as $entry) { $entry->order = $count; $entry->save(); $count++; } return true; }
/** * @param array $types * * @return Collection */ public function getActiveAccountsByType(array $types) : Collection { /** @var Collection $result */ $query = $this->user->accounts()->with(['accountmeta' => function (HasMany $query) { $query->where('name', 'accountRole'); }]); if (count($types) > 0) { $query->accountTypeIn($types); } $query->where('active', 1); $result = $query->get(['accounts.*']); $result = $result->sortBy(function (Account $account) { return strtolower($account->name); }); return $result; }
/** * @return bool */ protected function validateAccountAnonymously() { if (!isset($this->data['user_id'])) { return false; } $user = User::find($this->data['user_id']); $type = AccountType::find($this->data['account_type_id'])->first(); $value = $this->tryDecrypt($this->data['name']); $set = $user->accounts()->where('account_type_id', $type->id)->get(); /** @var Account $entry */ foreach ($set as $entry) { if ($entry->name == $value) { return false; } } return true; }
/** * @param Collection $accounts * @param Carbon $start * @param Carbon $end * * @return string */ public function spentInPeriodWithoutBudget(Collection $accounts, Carbon $start, Carbon $end) : string { $types = [TransactionType::WITHDRAWAL]; $query = $this->user->transactionJournals()->distinct()->transactionTypes($types)->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')->leftJoin('transactions as source', function (JoinClause $join) { $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')->where('source.amount', '<', 0); })->leftJoin('transactions as destination', function (JoinClause $join) { $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')->where('destination.amount', '>', 0); })->leftJoin('budget_transaction', 'source.id', '=', 'budget_transaction.transaction_id')->whereNull('budget_transaction_journal.id')->whereNull('budget_transaction.id')->before($end)->after($start)->whereNull('source.deleted_at')->whereNull('destination.deleted_at')->where('transaction_journals.completed', 1); if ($accounts->count() > 0) { $accountIds = $accounts->pluck('id')->toArray(); $set = join(', ', $accountIds); $query->whereRaw('(source.account_id in (' . $set . ') XOR destination.account_id in (' . $set . '))'); } $ids = $query->get(['transaction_journals.id'])->pluck('id')->toArray(); $sum = '0'; if (count($ids) > 0) { $sum = strval($this->user->transactions()->whereIn('transaction_journal_id', $ids)->where('amount', '<', '0')->whereNull('transactions.deleted_at')->sum('amount')); } return $sum; }
/** * Send a reset link to the given user. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function sendResetLinkEmail(Request $request) { $this->validate($request, ['email' => 'required|email']); $user = User::whereEmail($request->get('email'))->first(); if (!is_null($user) && intval($user->blocked) === 1) { $response = 'passwords.blocked'; } else { $response = Password::sendResetLink($request->only('email'), function (Message $message) { $message->subject($this->getEmailSubject()); }); } switch ($response) { case Password::RESET_LINK_SENT: return $this->getSendResetLinkEmailSuccessResponse($response); case Password::INVALID_USER: case 'passwords.blocked': default: return $this->getSendResetLinkEmailFailureResponse($response); } }
/** * Send a reset link to the given user. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function postEmail(Request $request) { $this->validate($request, ['email' => 'required|email']); $user = User::whereEmail($request->get('email'))->first(); if (!is_null($user) && intval($user->blocked) === 1) { $response = 'passwords.blocked'; } else { $response = Password::sendResetLink($request->only('email'), function (Message $message) { $message->subject($this->getEmailSubject()); }); } switch ($response) { case Password::RESET_LINK_SENT: return redirect()->back()->with('status', trans($response)); case Password::INVALID_USER: case 'passwords.blocked': return redirect()->back()->withErrors(['email' => trans($response)]); } abort(404); return ''; }
/** * @param array $data * * @return Rule */ public function store(array $data) : Rule { /** @var RuleGroup $ruleGroup */ $ruleGroup = $this->user->ruleGroups()->find($data['rule_group_id']); // get max order: $order = $this->getHighestOrderInRuleGroup($ruleGroup); // start by creating a new rule: $rule = new Rule(); $rule->user()->associate($data['user_id']); $rule->rule_group_id = $data['rule_group_id']; $rule->order = $order + 1; $rule->active = 1; $rule->stop_processing = intval($data['stop_processing']) == 1; $rule->title = $data['title']; $rule->description = strlen($data['description']) > 0 ? $data['description'] : null; $rule->save(); // start storing triggers: $this->storeTriggers($rule, $data); // same for actions. $this->storeActions($rule, $data); return $rule; }
/** * Returns a collection of ALL journals, given a specific account and a date range. * * @param Collection $accounts * @param Carbon $start * @param Carbon $end * * @return Collection */ public function getJournalsInRange(Collection $accounts, Carbon $start, Carbon $end) : Collection { $query = $this->user->transactionJournals()->expanded()->sortCorrectly(); $query->where('transaction_journals.completed', 1); $query->before($end); $query->after($start); if ($accounts->count() > 0) { $ids = $accounts->pluck('id')->toArray(); // join source and destination: $query->leftJoin('transactions as source', function (JoinClause $join) { $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')->where('source.amount', '<', 0); }); $query->leftJoin('transactions as destination', function (JoinClause $join) { $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')->where('destination.amount', '>', 0); }); $query->where(function (Builder $q) use($ids) { $q->whereIn('destination.account_id', $ids); $q->orWhereIn('source.account_id', $ids); }); } $set = $query->get(TransactionJournal::queryFields()); return $set; }
/** * @return Collection */ public function getPiggyBanks() : Collection { /** @var Collection $set */ $set = $this->user->piggyBanks()->orderBy('order', 'ASC')->get(); return $set; }
/** * @return Collection */ public function get() : Collection { return $this->user->attachments()->get(); }
/** * Create a new user instance after a valid registration. * * @param array $data * * @return User */ public function create(array $data) { return User::create(['email' => $data['email'], 'password' => $data['password']]); }
/** * @param DeleteAccountFormRequest $request * * @return \Illuminate\Http\RedirectResponse * @throws \Exception */ public function postDeleteAccount(DeleteAccountFormRequest $request) { // old, new1, new2 if (!Hash::check($request->get('password'), auth()->user()->password)) { Session::flash('error', strval(trans('firefly.invalid_password'))); return redirect(route('profile.delete-account')); } // respond to deletion: event(new UserIsDeleted(auth()->user(), $request->ip())); // store some stuff for the future: $registration = Preferences::get('registration_ip_address')->data; $confirmation = Preferences::get('confirmation_ip_address')->data; // DELETE! $email = auth()->user()->email; auth()->user()->delete(); Session::flush(); Session::flash('gaEventCategory', 'user'); Session::flash('gaEventAction', 'delete-account'); // create a new user with the same email address so re-registration is blocked. $newUser = User::create(['email' => $email, 'password' => 'deleted', 'blocked' => 1, 'blocked_code' => 'deleted']); if (strlen($registration) > 0) { Preferences::setForUser($newUser, 'registration_ip_address', $registration); } if (strlen($confirmation) > 0) { Preferences::setForUser($newUser, 'confirmation_ip_address', $confirmation); } return redirect(route('index')); }
/** * Show the application login form. * * @return \Illuminate\Http\Response */ public function showLoginForm(Request $request) { // is allowed to? $singleUserMode = FireflyConfig::get('single_user_mode', Config::get('firefly.configuration.single_user_mode'))->data; $userCount = User::count(); $allowRegistration = true; if ($singleUserMode === true && $userCount > 0) { $allowRegistration = false; } $email = $request->old('email'); $remember = $request->old('remember'); return view('auth.login', compact('allowRegistration', 'email', 'remember')); }
/** * @param User $user * @param $name * * @return Account|null */ public static function findAccount(User $user, $name) { /** @var Account $account */ foreach ($user->accounts()->get() as $account) { if ($account->name == $name) { Log::debug('Trying to find "' . $name . '" in "' . $account->name . '", and found it!'); return $account; } Log::debug('Trying to find "' . $name . '" in "' . $account->name . '".'); } return null; }
/** * @param $name * * @return PiggyBank|null */ protected function findPiggyBank($name) { // account $user = User::whereEmail('*****@*****.**')->first(); /** @var Budget $budget */ foreach (PiggyBank::get() as $piggyBank) { $account = $piggyBank->account()->first(); if ($piggyBank->name == $name && $user->id == $account->user_id) { return $piggyBank; break; } } return null; }
/** * @param DeleteAccountFormRequest $request * * @return \Illuminate\Http\RedirectResponse * @throws \Exception */ public function postDeleteAccount(DeleteAccountFormRequest $request) { // old, new1, new2 if (!Hash::check($request->get('password'), Auth::user()->password)) { Session::flash('error', trans('firefly.invalid_password')); return redirect(route('profile.delete-account')); } // DELETE! $email = Auth::user()->email; Auth::user()->delete(); Session::flush(); Session::flash('gaEventCategory', 'user'); Session::flash('gaEventAction', 'delete-account'); // create a new user with the same email address so re-registration is blocked. User::create(['email' => $email, 'password' => 'deleted', 'blocked' => 1, 'blocked_code' => 'deleted']); return redirect(route('index')); }
/** * @return User */ public function user() { return User::find(1); }
/** * Create a new user instance after a valid registration. * * @param array $data * * @return User */ protected function create(array $data) { return User::create(['email' => $data['email'], 'password' => bcrypt($data['password'])]); }
/** * @return array */ private function getKnownDomains() : array { $users = User::get(); $set = []; $filtered = []; /** @var User $user */ foreach ($users as $user) { $email = $user->email; $parts = explode('@', $email); $domain = $parts[1]; $set[] = $domain; } $set = array_unique($set); // filter for already banned domains: $blocked = FireflyConfig::get('blocked-domains', [])->data; foreach ($set as $domain) { // in the block array? ignore it. if (!in_array($domain, $blocked)) { $filtered[] = $domain; } } asort($filtered); return $filtered; }