├── public
├── favicon.ico
├── robots.txt
├── mix-manifest.json
├── .htaccess
├── web.config
├── js
│ └── app.js.LICENSE.txt
└── index.php
├── bootstrap
├── cache
│ └── .gitignore
└── app.php
├── storage
├── logs
│ └── .gitignore
├── app
│ ├── public
│ │ └── .gitignore
│ └── .gitignore
└── framework
│ ├── testing
│ └── .gitignore
│ ├── views
│ └── .gitignore
│ ├── cache
│ ├── data
│ │ └── .gitignore
│ └── .gitignore
│ ├── sessions
│ └── .gitignore
│ └── .gitignore
├── database
├── .gitignore
├── seeders
│ └── DatabaseSeeder.php
├── migrations
│ ├── 2021_08_17_114743_add_followup_to_elections.php
│ ├── 2014_10_12_100000_create_password_resets_table.php
│ ├── 2014_10_12_000000_create_users_table.php
│ ├── 2021_02_24_213344_create_countries_table.php
│ ├── 2021_02_24_213152_create_uploads_table.php
│ ├── 2019_08_19_000000_create_failed_jobs_table.php
│ ├── 2014_10_12_200000_add_two_factor_columns_to_users_table.php
│ ├── 2021_02_28_222507_create_parties_table.php
│ ├── 2021_05_17_130359_create_answers_table.php
│ ├── 2021_07_30_183603_add_locale_to_analytics_tables.php
│ ├── 2021_05_16_175828_create_questions_table.php
│ ├── 2021_05_15_105016_create_elections_table.php
│ ├── 2021_05_16_213233_create_election_parties_pivot.php
│ └── 2021_05_31_202541_create_statistics_table.php
└── factories
│ └── UserFactory.php
├── .prettierrc.js
├── resources
├── .DS_Store
├── css
│ └── app.css
├── js
│ ├── util
│ │ ├── cdn.tsx
│ │ ├── get-translated-value.tsx
│ │ └── create-date-from-mysql.ts
│ ├── config
│ │ ├── app.ts
│ │ └── locales.ts
│ ├── pages
│ │ ├── dashboard.tsx
│ │ ├── auth
│ │ │ ├── forgot-password.tsx
│ │ │ └── login.tsx
│ │ ├── statistic
│ │ │ └── election.tsx
│ │ └── users
│ │ │ └── index.tsx
│ ├── components
│ │ ├── image
│ │ │ └── index.tsx
│ │ ├── pass-link.tsx
│ │ ├── flags
│ │ │ ├── de.tsx
│ │ │ ├── sv.tsx
│ │ │ ├── fr.tsx
│ │ │ ├── fi.tsx
│ │ │ ├── world.tsx
│ │ │ └── us.tsx
│ │ ├── form
│ │ │ ├── input.tsx
│ │ │ ├── textarea.tsx
│ │ │ ├── select.tsx
│ │ │ ├── toggle.tsx
│ │ │ ├── answer.tsx
│ │ │ ├── translations.tsx
│ │ │ └── datepicker.tsx
│ │ ├── locale-with-flag.tsx
│ │ ├── page.tsx
│ │ └── locale-switch.tsx
│ ├── contexts
│ │ └── app.tsx
│ ├── app.tsx
│ └── types.d.ts
├── views
│ ├── emails
│ │ └── user
│ │ │ └── created.blade.php
│ └── app.blade.php
└── lang
│ └── en
│ ├── pagination.php
│ ├── auth.php
│ └── passwords.php
├── .gitattributes
├── .vscode
└── settings.json
├── config
├── translatable.php
├── eloquent-sortable.php
├── cors.php
├── services.php
├── view.php
├── hashing.php
├── broadcasting.php
├── filesystems.php
├── queue.php
├── logging.php
├── cache.php
└── mail.php
├── tests
├── TestCase.php
├── Unit
│ └── ExampleTest.php
├── Feature
│ └── ExampleTest.php
└── CreatesApplication.php
├── .styleci.yml
├── .gitignore
├── .editorconfig
├── app
├── Http
│ ├── Controllers
│ │ ├── Admin
│ │ │ ├── DashboardController.php
│ │ │ ├── CacheController.php
│ │ │ ├── StatisticController.php
│ │ │ ├── UserController.php
│ │ │ ├── PartyController.php
│ │ │ └── CountryController.php
│ │ ├── Controller.php
│ │ └── Api
│ │ │ └── V1
│ │ │ ├── StatisticController.php
│ │ │ ├── QuestionController.php
│ │ │ ├── PartyController.php
│ │ │ └── CountryController.php
│ ├── Middleware
│ │ ├── EncryptCookies.php
│ │ ├── VerifyCsrfToken.php
│ │ ├── TrimStrings.php
│ │ ├── TrustHosts.php
│ │ ├── PreventRequestsDuringMaintenance.php
│ │ ├── Authenticate.php
│ │ ├── TrustProxies.php
│ │ ├── SetLocale.php
│ │ ├── RedirectIfAuthenticated.php
│ │ ├── HandleInertiaRequests.php
│ │ └── LocalizeApi.php
│ ├── Requests
│ │ ├── StoreAnswers.php
│ │ ├── CreateOrEditUser.php
│ │ ├── AttachOrSyncParty.php
│ │ ├── CreateOrEditCountry.php
│ │ ├── CreateOrEditQuestion.php
│ │ ├── CreateOrEditParty.php
│ │ └── CreateOrEditElection.php
│ └── Kernel.php
├── Actions
│ └── Fortify
│ │ ├── PasswordValidationRules.php
│ │ ├── ResetUserPassword.php
│ │ ├── CreateNewUser.php
│ │ ├── UpdateUserPassword.php
│ │ └── UpdateUserProfileInformation.php
├── Providers
│ ├── BroadcastServiceProvider.php
│ ├── AppServiceProvider.php
│ ├── AuthServiceProvider.php
│ ├── EventServiceProvider.php
│ ├── RouteServiceProvider.php
│ └── FortifyServiceProvider.php
├── Models
│ ├── Initiation.php
│ ├── Result.php
│ ├── Swipe.php
│ ├── Answer.php
│ ├── User.php
│ ├── ElectionParty.php
│ ├── Question.php
│ ├── Party.php
│ ├── Country.php
│ ├── Election.php
│ └── Upload.php
├── Traits
│ └── HasTranslations.php
├── Exceptions
│ └── Handler.php
├── Console
│ └── Kernel.php
├── Jobs
│ ├── InitiateSwiper.php
│ ├── CountAnswer.php
│ └── SaveResult.php
└── Mail
│ └── UserInAdminCreated.php
├── webpack.mix.js
├── routes
├── channels.php
├── console.php
└── api.php
├── server.php
├── tsconfig.json
├── .env.example
├── phpunit.xml
├── README.md
├── artisan
├── package.json
├── docker-compose.yml
├── composer.json
└── .eslintrc.js
/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/bootstrap/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/database/.gitignore:
--------------------------------------------------------------------------------
1 | *.sqlite
2 | *.sqlite-journal
3 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | User-agent: *
2 | Disallow:
3 |
--------------------------------------------------------------------------------
/storage/app/public/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/app/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !public/
3 | !.gitignore
4 |
--------------------------------------------------------------------------------
/storage/framework/testing/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/views/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/cache/data/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/sessions/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !data/
3 | !.gitignore
4 |
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | semi: true,
3 | singleQuote: true
4 | }
5 |
--------------------------------------------------------------------------------
/resources/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MOVACT/voteswiper-api/HEAD/resources/.DS_Store
--------------------------------------------------------------------------------
/public/mix-manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "/js/app.js": "/js/app.js",
3 | "/css/app.css": "/css/app.css"
4 | }
5 |
--------------------------------------------------------------------------------
/resources/css/app.css:
--------------------------------------------------------------------------------
1 | @import "~@tabler/core/dist/css/tabler.css";
2 | @import "~react-datepicker/dist/react-datepicker.css";
3 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 | *.css linguist-vendored
3 | *.scss linguist-vendored
4 | *.js linguist-vendored
5 | CHANGELOG.md export-ignore
6 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "editor.formatOnSave": false,
3 | "editor.codeActionsOnSave": {
4 | "source.fixAll.eslint": "explicit"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/storage/framework/.gitignore:
--------------------------------------------------------------------------------
1 | compiled.php
2 | config.php
3 | down
4 | events.scanned.php
5 | maintenance.php
6 | routes.php
7 | routes.scanned.php
8 | schedule-*
9 | services.json
10 |
--------------------------------------------------------------------------------
/resources/js/util/cdn.tsx:
--------------------------------------------------------------------------------
1 | import app from '../config/app';
2 |
3 | const cdn = (fileName: string): string => {
4 | return app.assetsPublicUrl + fileName;
5 | };
6 |
7 | export default cdn;
8 |
--------------------------------------------------------------------------------
/config/translatable.php:
--------------------------------------------------------------------------------
1 | null,
9 | ];
10 |
--------------------------------------------------------------------------------
/tests/TestCase.php:
--------------------------------------------------------------------------------
1 | $url])
9 | Login
10 | @endcomponent
11 |
12 | @endcomponent
13 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Admin/DashboardController.php:
--------------------------------------------------------------------------------
1 | assertTrue(true);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/resources/js/util/get-translated-value.tsx:
--------------------------------------------------------------------------------
1 | export const getTranslatedValue = (
2 | column: TranslatedColumn,
3 | locale: string,
4 | defaultValue?: string
5 | ): string => {
6 | if (column[locale]) {
7 | return column[locale];
8 | }
9 |
10 | if (defaultValue) {
11 | return defaultValue;
12 | }
13 |
14 | return '';
15 | };
16 |
--------------------------------------------------------------------------------
/database/seeders/DatabaseSeeder.php:
--------------------------------------------------------------------------------
1 | create();
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/Http/Middleware/EncryptCookies.php:
--------------------------------------------------------------------------------
1 | 'sort_order',
8 |
9 | /*
10 | * Define if the models should sort when creating.
11 | * When true, the package will automatically assign the highest order number to a new mode
12 | */
13 | 'sort_when_creating' => true,
14 | ];
15 |
--------------------------------------------------------------------------------
/app/Http/Middleware/VerifyCsrfToken.php:
--------------------------------------------------------------------------------
1 | get('/');
18 |
19 | $response->assertStatus(200);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/app/Http/Middleware/TrustHosts.php:
--------------------------------------------------------------------------------
1 | allSubdomainsOfApplicationUrl(),
18 | ];
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/app/Http/Middleware/PreventRequestsDuringMaintenance.php:
--------------------------------------------------------------------------------
1 | {
7 | return (
8 |
9 |
10 |
11 | );
12 | };
13 |
14 | Dashboard.layout = (page) => {page};
15 |
16 | export default Dashboard;
17 |
--------------------------------------------------------------------------------
/resources/views/app.blade.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | @routes
7 |
8 |
9 |
10 |
11 | @inertia
12 |
13 |
14 |
--------------------------------------------------------------------------------
/tests/CreatesApplication.php:
--------------------------------------------------------------------------------
1 | make(Kernel::class)->bootstrap();
19 |
20 | return $app;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/Providers/BroadcastServiceProvider.php:
--------------------------------------------------------------------------------
1 | back()->with(['success' => 'The cache has been cleared successfully.']);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/Http/Middleware/Authenticate.php:
--------------------------------------------------------------------------------
1 | expectsJson()) {
18 | return route('login');
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/resources/js/components/image/index.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import cdn from '../../util/cdn';
3 |
4 | interface Props {
5 | file: Upload;
6 | }
7 |
8 | const Image: React.FC = ({ file }) => {
9 | return (
10 |
11 |
})
18 |
19 | );
20 | };
21 |
22 | export default Image;
23 |
--------------------------------------------------------------------------------
/resources/lang/en/pagination.php:
--------------------------------------------------------------------------------
1 | '« Previous',
17 | 'next' => 'Next »',
18 |
19 | ];
20 |
--------------------------------------------------------------------------------
/webpack.mix.js:
--------------------------------------------------------------------------------
1 | const mix = require('laravel-mix');
2 |
3 | /*
4 | |--------------------------------------------------------------------------
5 | | Mix Asset Management
6 | |--------------------------------------------------------------------------
7 | |
8 | | Mix provides a clean, fluent API for defining some Webpack build steps
9 | | for your Laravel applications. By default, we are compiling the CSS
10 | | file for the application as well as bundling up all the JS files.
11 | |
12 | */
13 |
14 | mix.ts('resources/js/app.tsx', 'public/js')
15 | .postCss('resources/css/app.css', 'public/css', [
16 | //
17 | ]);
18 |
--------------------------------------------------------------------------------
/routes/channels.php:
--------------------------------------------------------------------------------
1 | id === (int) $id;
18 | });
19 |
--------------------------------------------------------------------------------
/resources/js/components/pass-link.tsx:
--------------------------------------------------------------------------------
1 | import { Inertia } from '@inertiajs/inertia';
2 | import React from 'react';
3 |
4 | interface Props {
5 | href: string;
6 | }
7 |
8 | export const PassLink: React.FC = ({ children, href }) => {
9 | const visit = (
10 | event: React.MouseEvent
11 | ): void => {
12 | event.preventDefault();
13 | Inertia.visit(href);
14 | };
15 |
16 | return React.cloneElement(
17 | children as React.DetailedReactHTMLElement,
18 | {
19 | onClick: visit,
20 | href,
21 | }
22 | );
23 | };
24 |
--------------------------------------------------------------------------------
/server.php:
--------------------------------------------------------------------------------
1 |
8 | */
9 |
10 | $uri = urldecode(
11 | parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
12 | );
13 |
14 | // This file allows us to emulate Apache's "mod_rewrite" functionality from the
15 | // built-in PHP web server. This provides a convenient way to test a Laravel
16 | // application without having installed a "real" web server software here.
17 | if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
18 | return false;
19 | }
20 |
21 | require_once __DIR__.'/public/index.php';
22 |
--------------------------------------------------------------------------------
/app/Models/Initiation.php:
--------------------------------------------------------------------------------
1 | belongsTo(Election::class);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/Traits/HasTranslations.php:
--------------------------------------------------------------------------------
1 | getTranslatableAttributes() as $field) {
19 | $attributes[$field] = $this->getTranslation($field, App::getLocale());
20 | }
21 | return $attributes;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/routes/console.php:
--------------------------------------------------------------------------------
1 | comment(Inspiring::quote());
19 | })->purpose('Display an inspiring quote');
20 |
--------------------------------------------------------------------------------
/public/.htaccess:
--------------------------------------------------------------------------------
1 |
2 |
3 | Options -MultiViews -Indexes
4 |
5 |
6 | RewriteEngine On
7 |
8 | # Handle Authorization Header
9 | RewriteCond %{HTTP:Authorization} .
10 | RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
11 |
12 | # Redirect Trailing Slashes If Not A Folder...
13 | RewriteCond %{REQUEST_FILENAME} !-d
14 | RewriteCond %{REQUEST_URI} (.+)/$
15 | RewriteRule ^ %1 [L,R=301]
16 |
17 | # Send Requests To Front Controller...
18 | RewriteCond %{REQUEST_FILENAME} !-d
19 | RewriteCond %{REQUEST_FILENAME} !-f
20 | RewriteRule ^ index.php [L]
21 |
22 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "strictNullChecks": true,
12 | "esModuleInterop": true,
13 | "allowSyntheticDefaultImports": true,
14 | "strict": true,
15 | "forceConsistentCasingInFileNames": true,
16 | "module": "esnext",
17 | "moduleResolution": "node",
18 | "resolveJsonModule": true,
19 | "isolatedModules": true,
20 | "jsx": "react",
21 | },
22 | "include": [
23 | "resources/js"
24 | ],
25 | "exclude": [
26 | "node_modules"
27 | ]
28 | }
29 |
--------------------------------------------------------------------------------
/app/Providers/AuthServiceProvider.php:
--------------------------------------------------------------------------------
1 | 'App\Policies\ModelPolicy',
17 | ];
18 |
19 | /**
20 | * Register any authentication / authorization services.
21 | *
22 | * @return void
23 | */
24 | public function boot()
25 | {
26 | $this->registerPolicies();
27 |
28 | //
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/resources/js/util/create-date-from-mysql.ts:
--------------------------------------------------------------------------------
1 | const createDateFromMysql = (mysql_string: string): Date | null => {
2 | let t,
3 | result = null;
4 |
5 | if (typeof mysql_string === 'string') {
6 | t = mysql_string.split(/[- :]/);
7 |
8 | //when t[3], t[4] and t[5] are missing they defaults to zero
9 | result = new Date(
10 | Date.UTC(
11 | parseInt(t[0]),
12 | parseInt(t[1]) - 1,
13 | parseInt(t[2]),
14 | parseInt(t[3]) || 0,
15 | parseInt(t[4]) || 0,
16 | parseInt(t[5]) || 0
17 | )
18 | );
19 | }
20 |
21 | return result;
22 | };
23 |
24 | export default createDateFromMysql;
25 |
--------------------------------------------------------------------------------
/app/Http/Middleware/TrustProxies.php:
--------------------------------------------------------------------------------
1 | 'These credentials do not match our records.',
17 | 'password' => 'The provided password is incorrect.',
18 | 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
19 |
20 | ];
21 |
--------------------------------------------------------------------------------
/app/Models/Result.php:
--------------------------------------------------------------------------------
1 | 'array',
28 | ];
29 |
30 | public function election(): BelongsTo
31 | {
32 | return $this->belongsTo(Election::class);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/resources/js/contexts/app.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { useLocalStorage } from 'react-use';
3 |
4 | interface AppContext {
5 | drawerOpen: boolean | undefined;
6 | setDrawerOpen: (drawerOpen: boolean) => void;
7 | }
8 |
9 | const AppContext = React.createContext({} as AppContext);
10 |
11 | const AppProvider: React.FC = ({ children }) => {
12 | const [drawerOpen, setDrawerOpen] = useLocalStorage<
13 | AppContext['drawerOpen']
14 | >('admin:drawer', false);
15 |
16 | return (
17 |
18 | {children}
19 |
20 | );
21 | };
22 |
23 | const useApp = (): AppContext => React.useContext(AppContext);
24 |
25 | export { AppProvider, useApp };
26 |
--------------------------------------------------------------------------------
/app/Http/Middleware/SetLocale.php:
--------------------------------------------------------------------------------
1 | has('locale')) {
23 | app()->setLocale(session('locale'));
24 | } else {
25 | app()->setLocale(config('app.locale'));
26 | }
27 | return $next($request);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/Models/Swipe.php:
--------------------------------------------------------------------------------
1 | belongsTo(Election::class);
29 | }
30 |
31 | public function question(): BelongsTo
32 | {
33 | return $this->belongsTo(Question::class);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/database/migrations/2021_08_17_114743_add_followup_to_elections.php:
--------------------------------------------------------------------------------
1 | json('followup_link');
18 | });
19 | }
20 |
21 | /**
22 | * Reverse the migrations.
23 | *
24 | * @return void
25 | */
26 | public function down()
27 | {
28 | Schema::table('elections', function (Blueprint $table) {
29 | $table->dropColumn('followup_link');
30 | });
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/app/Actions/Fortify/ResetUserPassword.php:
--------------------------------------------------------------------------------
1 | $this->passwordRules(),
24 | ])->validate();
25 |
26 | $user->forceFill([
27 | 'password' => Hash::make($input['password']),
28 | ])->save();
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/Providers/EventServiceProvider.php:
--------------------------------------------------------------------------------
1 | [
19 | SendEmailVerificationNotification::class,
20 | ],
21 | ];
22 |
23 | /**
24 | * Register any events for your application.
25 | *
26 | * @return void
27 | */
28 | public function boot()
29 | {
30 | //
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/resources/js/components/flags/de.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export const FlagDE: React.FC> = (props) => {
4 | return (
5 |
19 | );
20 | };
21 |
--------------------------------------------------------------------------------
/resources/lang/en/passwords.php:
--------------------------------------------------------------------------------
1 | 'Your password has been reset!',
17 | 'sent' => 'We have emailed your password reset link!',
18 | 'throttled' => 'Please wait before retrying.',
19 | 'token' => 'This password reset token is invalid.',
20 | 'user' => "We can't find a user with that email address.",
21 |
22 | ];
23 |
--------------------------------------------------------------------------------
/database/migrations/2014_10_12_100000_create_password_resets_table.php:
--------------------------------------------------------------------------------
1 | string('email')->index();
18 | $table->string('token');
19 | $table->timestamp('created_at')->nullable();
20 | });
21 | }
22 |
23 | /**
24 | * Reverse the migrations.
25 | *
26 | * @return void
27 | */
28 | public function down()
29 | {
30 | Schema::dropIfExists('password_resets');
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/resources/js/components/flags/sv.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export const FlagSV: React.FC> = (props) => {
4 | return (
5 |
22 | );
23 | };
24 |
--------------------------------------------------------------------------------
/app/Http/Middleware/RedirectIfAuthenticated.php:
--------------------------------------------------------------------------------
1 | check()) {
26 | return redirect(RouteServiceProvider::HOME);
27 | }
28 | }
29 |
30 | return $next($request);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/app/Exceptions/Handler.php:
--------------------------------------------------------------------------------
1 | reportable(function (Throwable $e) {
38 | //
39 | });
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/app/Http/Requests/StoreAnswers.php:
--------------------------------------------------------------------------------
1 | election->questions()->get();
28 | $rules = [];
29 |
30 | foreach($questions as $question) {
31 | $rules['answer_' . $question->id] = 'required|digits_between:0,2';
32 | $rules['reason_' . $question->id] = 'string||nullable';
33 | }
34 |
35 | return $rules;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/resources/js/components/flags/fr.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export const FlagFR: React.FC> = (props) => {
4 | return (
5 |
25 | );
26 | };
27 |
--------------------------------------------------------------------------------
/config/cors.php:
--------------------------------------------------------------------------------
1 | ['api/*', 'sanctum/csrf-cookie'],
19 |
20 | 'allowed_methods' => ['*'],
21 |
22 | 'allowed_origins' => ['*'],
23 |
24 | 'allowed_origins_patterns' => [],
25 |
26 | 'allowed_headers' => ['*'],
27 |
28 | 'exposed_headers' => [],
29 |
30 | 'max_age' => 0,
31 |
32 | 'supports_credentials' => false,
33 |
34 | ];
35 |
--------------------------------------------------------------------------------
/database/migrations/2014_10_12_000000_create_users_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->string('name');
19 | $table->string('email')->unique();
20 | $table->timestamp('email_verified_at')->nullable();
21 | $table->string('password');
22 | $table->rememberToken();
23 | $table->timestamps();
24 | });
25 | }
26 |
27 | /**
28 | * Reverse the migrations.
29 | *
30 | * @return void
31 | */
32 | public function down()
33 | {
34 | Schema::dropIfExists('users');
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/app/Console/Kernel.php:
--------------------------------------------------------------------------------
1 | command('inspire')->hourly();
28 | }
29 |
30 | /**
31 | * Register the commands for the application.
32 | *
33 | * @return void
34 | */
35 | protected function commands()
36 | {
37 | $this->load(__DIR__.'/Commands');
38 |
39 | require base_path('routes/console.php');
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/database/migrations/2021_02_24_213344_create_countries_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->string('country_code', 10);
19 | $table->string('language_code', 10);
20 | $table->json('name');
21 | $table->json('slug');
22 | $table->boolean('published')->default(false);
23 | $table->timestamps();
24 | });
25 | }
26 |
27 | /**
28 | * Reverse the migrations.
29 | *
30 | * @return void
31 | */
32 | public function down()
33 | {
34 | Schema::dropIfExists('countries');
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/resources/js/app.tsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable @typescript-eslint/no-var-requires */
2 | import { InertiaApp } from '@inertiajs/inertia-react';
3 | import { InertiaProgress } from '@inertiajs/progress';
4 | import React from 'react';
5 | import { render } from 'react-dom';
6 | import { Helmet } from 'react-helmet';
7 | import { AppProvider } from './contexts/app';
8 |
9 | InertiaProgress.init({
10 | includeCSS: true,
11 | });
12 |
13 | const el = document.getElementById('app');
14 |
15 | const App: React.FC = () => {
16 | return (
17 |
18 |
19 | {el && (
20 |
23 | require(`./pages/${name}`).default
24 | }
25 | />
26 | )}
27 |
28 | );
29 | };
30 |
31 | render(, el);
32 |
--------------------------------------------------------------------------------
/database/migrations/2021_02_24_213152_create_uploads_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->json('filename');
19 | $table->json('filetype');
20 | $table->json('width');
21 | $table->json('height');
22 | $table->json('filesize');
23 | $table->json('alt_text')->nullable();
24 | $table->timestamps();
25 | });
26 | }
27 |
28 | /**
29 | * Reverse the migrations.
30 | *
31 | * @return void
32 | */
33 | public function down()
34 | {
35 | Schema::dropIfExists('uploads');
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/database/migrations/2019_08_19_000000_create_failed_jobs_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->string('uuid')->unique();
19 | $table->text('connection');
20 | $table->text('queue');
21 | $table->longText('payload');
22 | $table->longText('exception');
23 | $table->timestamp('failed_at')->useCurrent();
24 | });
25 | }
26 |
27 | /**
28 | * Reverse the migrations.
29 | *
30 | * @return void
31 | */
32 | public function down()
33 | {
34 | Schema::dropIfExists('failed_jobs');
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/resources/js/components/flags/fi.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export const FlagFI: React.FC> = (props) => {
4 | return (
5 |
28 | );
29 | };
30 |
--------------------------------------------------------------------------------
/app/Models/Answer.php:
--------------------------------------------------------------------------------
1 | belongsTo(ElectionParty::class);
38 | }
39 |
40 | public function question(): BelongsTo
41 | {
42 | return $this->belongsTo(Question::class);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/Http/Requests/CreateOrEditUser.php:
--------------------------------------------------------------------------------
1 | 'string|required',
30 | 'email' => [
31 | 'string',
32 | 'email',
33 | 'required',
34 | $this->user
35 | ? Rule::unique('users', 'email')->ignore($this->user->id)
36 | : 'unique:users,email'
37 | ],
38 | ];
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/Models/User.php:
--------------------------------------------------------------------------------
1 | 'datetime',
44 | ];
45 | }
46 |
--------------------------------------------------------------------------------
/config/services.php:
--------------------------------------------------------------------------------
1 | [
18 | 'domain' => env('MAILGUN_DOMAIN'),
19 | 'secret' => env('MAILGUN_SECRET'),
20 | 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
21 | ],
22 |
23 | 'postmark' => [
24 | 'token' => env('POSTMARK_TOKEN'),
25 | ],
26 |
27 | 'ses' => [
28 | 'key' => env('AWS_ACCESS_KEY_ID'),
29 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
30 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
31 | ],
32 |
33 | ];
34 |
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | APP_NAME=Laravel
2 | APP_ENV=local
3 | APP_KEY=
4 | APP_DEBUG=true
5 | APP_URL=http://localhost
6 |
7 | LOG_CHANNEL=stack
8 | LOG_LEVEL=debug
9 |
10 | DB_CONNECTION=mysql
11 | DB_HOST=127.0.0.1
12 | DB_PORT=3306
13 | DB_DATABASE=voteswiper_api
14 | DB_USERNAME=root
15 | DB_PASSWORD=
16 |
17 | BROADCAST_DRIVER=log
18 | CACHE_DRIVER=file
19 | QUEUE_CONNECTION=sync
20 | SESSION_DRIVER=file
21 | SESSION_LIFETIME=120
22 |
23 | MEMCACHED_HOST=127.0.0.1
24 |
25 | REDIS_HOST=127.0.0.1
26 | REDIS_PASSWORD=null
27 | REDIS_PORT=6379
28 |
29 | MAIL_MAILER=smtp
30 | MAIL_HOST=mailhog
31 | MAIL_PORT=1025
32 | MAIL_USERNAME=null
33 | MAIL_PASSWORD=null
34 | MAIL_ENCRYPTION=null
35 | MAIL_FROM_ADDRESS=null
36 | MAIL_FROM_NAME="${APP_NAME}"
37 |
38 | AWS_ACCESS_KEY_ID=
39 | AWS_SECRET_ACCESS_KEY=
40 | AWS_DEFAULT_REGION=us-east-1
41 | AWS_BUCKET=
42 |
43 | PUSHER_APP_ID=
44 | PUSHER_APP_KEY=
45 | PUSHER_APP_SECRET=
46 | PUSHER_APP_CLUSTER=mt1
47 |
48 | MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
49 | MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
50 |
51 | API_SUBTYPE=voteswiper
52 | API_PREFIX=api
53 | API_NAME=VoteSwiper
54 |
--------------------------------------------------------------------------------
/resources/js/components/form/input.tsx:
--------------------------------------------------------------------------------
1 | import cn from 'classnames';
2 | import React from 'react';
3 |
4 | interface Props
5 | extends React.DetailedHTMLProps<
6 | React.InputHTMLAttributes,
7 | HTMLInputElement
8 | > {
9 | label?: string;
10 | error: boolean;
11 | helperText?: string | React.ReactNode;
12 | }
13 |
14 | const Input: React.FC = ({ label, error, helperText, ...restProps }) => {
15 | return (
16 |
17 | {label &&
}
18 |
19 |
24 | {helperText && (
25 |
26 | {helperText}
27 |
28 | )}
29 |
30 |
31 | );
32 | };
33 |
34 | export default Input;
35 |
--------------------------------------------------------------------------------
/database/migrations/2014_10_12_200000_add_two_factor_columns_to_users_table.php:
--------------------------------------------------------------------------------
1 | text('two_factor_secret')
18 | ->after('password')
19 | ->nullable();
20 |
21 | $table->text('two_factor_recovery_codes')
22 | ->after('two_factor_secret')
23 | ->nullable();
24 | });
25 | }
26 |
27 | /**
28 | * Reverse the migrations.
29 | *
30 | * @return void
31 | */
32 | public function down()
33 | {
34 | Schema::table('users', function (Blueprint $table) {
35 | $table->dropColumn('two_factor_secret', 'two_factor_recovery_codes');
36 | });
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/Http/Requests/AttachOrSyncParty.php:
--------------------------------------------------------------------------------
1 | 'boolean|required',
29 | 'playable' => 'boolean|required',
30 | 'program_link' => 'string|url|nullable',
31 | ];
32 |
33 | $rules['program'] = 'file|nullable|max:15360|mimes:pdf';
34 | $rules['program_upload_id'] = 'integer|nullable|exists:uploads,id';
35 |
36 | if (!$this->party) {
37 | $rules['party_id'] = 'integer|required|exists:parties,id';
38 | }
39 |
40 | return $rules;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/Http/Requests/CreateOrEditCountry.php:
--------------------------------------------------------------------------------
1 | 'string|required',
30 | 'country_code' => [
31 | 'string',
32 | 'required',
33 | $this->country
34 | ? Rule::unique('countries', 'country_code')->ignore($this->country->id)
35 | : 'unique:countries,country_code'],
36 | 'language_code' => 'string|required',
37 | 'published' => 'boolean|required',
38 | ];
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/resources/js/components/form/textarea.tsx:
--------------------------------------------------------------------------------
1 | import cn from 'classnames';
2 | import React from 'react';
3 |
4 | interface Props
5 | extends React.DetailedHTMLProps<
6 | React.TextareaHTMLAttributes,
7 | HTMLTextAreaElement
8 | > {
9 | label?: string;
10 | error: boolean;
11 | helperText?: string | React.ReactNode;
12 | }
13 |
14 | const Textarea: React.FC = ({
15 | label,
16 | error,
17 | helperText,
18 | ...restProps
19 | }) => {
20 | return (
21 |
22 | {label &&
}
23 |
24 |
29 | {helperText && (
30 |
31 | {helperText}
32 |
33 | )}
34 |
35 |
36 | );
37 | };
38 |
39 | export default Textarea;
40 |
--------------------------------------------------------------------------------
/resources/js/components/form/select.tsx:
--------------------------------------------------------------------------------
1 | import cn from 'classnames';
2 | import React from 'react';
3 |
4 | interface Props
5 | extends React.DetailedHTMLProps<
6 | React.SelectHTMLAttributes,
7 | HTMLSelectElement
8 | > {
9 | label?: string;
10 | error: boolean;
11 | helperText?: boolean;
12 | }
13 |
14 | const Select: React.FC = ({
15 | label,
16 | error,
17 | helperText,
18 | children,
19 | ...restProps
20 | }) => {
21 | return (
22 |
23 | {label &&
}
24 |
25 |
31 |
32 | {helperText && (
33 |
34 | {helperText}
35 |
36 | )}
37 |
38 |
39 | );
40 | };
41 |
42 | export default Select;
43 |
--------------------------------------------------------------------------------
/config/view.php:
--------------------------------------------------------------------------------
1 | [
17 | resource_path('views'),
18 | ],
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Compiled View Path
23 | |--------------------------------------------------------------------------
24 | |
25 | | This option determines where all the compiled Blade templates will be
26 | | stored for your application. Typically, this is within the storage
27 | | directory. However, as usual, you are free to change this value.
28 | |
29 | */
30 |
31 | 'compiled' => env(
32 | 'VIEW_COMPILED_PATH',
33 | realpath(storage_path('framework/views'))
34 | ),
35 |
36 | ];
37 |
--------------------------------------------------------------------------------
/app/Actions/Fortify/CreateNewUser.php:
--------------------------------------------------------------------------------
1 | ['required', 'string', 'max:255'],
25 | 'email' => [
26 | 'required',
27 | 'string',
28 | 'email',
29 | 'max:255',
30 | Rule::unique(User::class),
31 | ],
32 | 'password' => $this->passwordRules(),
33 | ])->validate();
34 |
35 | return User::create([
36 | 'name' => $input['name'],
37 | 'email' => $input['email'],
38 | 'password' => Hash::make($input['password']),
39 | ]);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/resources/js/components/form/toggle.tsx:
--------------------------------------------------------------------------------
1 | import cn from 'classnames';
2 | import React from 'react';
3 |
4 | interface Props
5 | extends React.DetailedHTMLProps<
6 | React.InputHTMLAttributes,
7 | HTMLInputElement
8 | > {
9 | label: string;
10 | error: boolean;
11 | helperText?: string | React.ReactNode;
12 | }
13 |
14 | const Toggle: React.FC = ({
15 | label,
16 | error,
17 | helperText,
18 | ...restProps
19 | }) => {
20 | return (
21 |
22 |
32 | {helperText && (
33 |
34 | {helperText}
35 |
36 | )}
37 |
38 | );
39 | };
40 |
41 | export default Toggle;
42 |
--------------------------------------------------------------------------------
/app/Models/ElectionParty.php:
--------------------------------------------------------------------------------
1 | 'boolean',
33 | 'playable' => 'boolean',
34 | ];
35 |
36 | public function answers(): HasMany
37 | {
38 | return $this->hasMany(Answer::class, 'electionparty_id');
39 | }
40 |
41 | /**
42 | * Get the uploaded file
43 | */
44 | public function program(): BelongsTo
45 | {
46 | return $this->belongsTo(Upload::class, 'program_upload_id', 'id');
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/resources/js/components/locale-with-flag.tsx:
--------------------------------------------------------------------------------
1 | import { Page } from '@inertiajs/inertia';
2 | import { usePage } from '@inertiajs/inertia-react';
3 | import React from 'react';
4 | import locales from '../config/locales';
5 | import { FlagWorld } from './flags/world';
6 |
7 | interface Props {
8 | locale?: string;
9 | }
10 |
11 | export const LocaleWithFlag: React.FC = ({ locale }) => {
12 | const { props } = usePage>();
13 |
14 | const localeToShow = locale ? locale : props.locale;
15 |
16 | const renderComponent = (
17 | Component: React.FC>,
18 | label: string
19 | ): React.ReactElement => {
20 | return (
21 |
22 |
23 |
24 |
25 |
{label}
26 |
27 | );
28 | };
29 |
30 | if (locales[localeToShow]) {
31 | return renderComponent(
32 | locales[localeToShow].flag,
33 | locales[localeToShow].label
34 | );
35 | }
36 |
37 | return renderComponent(FlagWorld, localeToShow);
38 | };
39 |
--------------------------------------------------------------------------------
/app/Http/Requests/CreateOrEditQuestion.php:
--------------------------------------------------------------------------------
1 | 'string|required',
29 | 'thesis' => 'string|required',
30 | 'video_url' => 'string|url|nullable',
31 | 'explainer_text' => 'string|nullable',
32 | ];
33 |
34 | if ($this->question) {
35 | $rules['thumbnail'] = 'image|nullable|max:1024|mimes:jpeg,png,gif';
36 | $rules['thumbnail_upload_id'] = 'integer|required|exists:uploads,id';
37 | } else {
38 | $rules['thumbnail'] = 'image|required|max:1024|mimes:jpeg,png,gif';
39 | }
40 |
41 | return $rules;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/app/Actions/Fortify/UpdateUserPassword.php:
--------------------------------------------------------------------------------
1 | ['required', 'string'],
24 | 'password' => $this->passwordRules(),
25 | ])->after(function ($validator) use ($user, $input) {
26 | if (! isset($input['current_password']) || ! Hash::check($input['current_password'], $user->password)) {
27 | $validator->errors()->add('current_password', __('The provided password does not match your current password.'));
28 | }
29 | })->validateWithBag('updatePassword');
30 |
31 | $user->forceFill([
32 | 'password' => Hash::make($input['password']),
33 | ])->save();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/app/Http/Requests/CreateOrEditParty.php:
--------------------------------------------------------------------------------
1 | 'integer|required|exists:countries,id',
30 | 'name' => 'string|required',
31 | 'full_name' => 'string|required',
32 | 'url' => 'string|nullable',
33 | ];
34 |
35 | if ($this->party) {
36 | $rules['logo'] = 'image|nullable|max:1024|mimes:jpeg,png,gif';
37 | $rules['logo_upload_id'] = 'integer|required|exists:uploads,id';
38 | } else {
39 | $rules['logo'] = 'image|required|max:1024|mimes:jpeg,png,gif';
40 | }
41 |
42 | return $rules;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/Jobs/InitiateSwiper.php:
--------------------------------------------------------------------------------
1 | election_id = $election_id;
29 | $this->platform = $platform;
30 | $this->locale = $locale;
31 | }
32 |
33 | /**
34 | * Execute the job.
35 | *
36 | * @return void
37 | */
38 | public function handle()
39 | {
40 | Initiation::create([
41 | 'election_id' => $this->election_id,
42 | 'platform' => $this->platform,
43 | 'locale' => $this->locale
44 | ]);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/resources/js/components/flags/world.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export const FlagWorld: React.FC> = (props) => {
4 | return (
5 |
22 | );
23 | };
24 |
--------------------------------------------------------------------------------
/public/web.config:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | ./tests/Unit
10 |
11 |
12 | ./tests/Feature
13 |
14 |
15 |
16 |
17 | ./app
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/database/migrations/2021_02_28_222507_create_parties_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->foreignId('country_id')
19 | ->constrained()
20 | ->onUpdate('no action')
21 | ->onDelete('cascade');
22 | $table->string('name');
23 | $table->string('slug');
24 | $table->string('full_name');
25 | $table->string('url')->nullable();
26 | $table->unsignedBigInteger('logo_upload_id')->nullable();
27 | $table->foreign('logo_upload_id')
28 | ->references('id')->on('uploads')
29 | ->onDelete('set null');
30 | $table->timestamps();
31 | });
32 | }
33 |
34 | /**
35 | * Reverse the migrations.
36 | *
37 | * @return void
38 | */
39 | public function down()
40 | {
41 | Schema::dropIfExists('parties');
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/database/factories/UserFactory.php:
--------------------------------------------------------------------------------
1 | $this->faker->name,
27 | 'email' => $this->faker->unique()->safeEmail,
28 | 'email_verified_at' => now(),
29 | 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
30 | 'remember_token' => Str::random(10),
31 | ];
32 | }
33 |
34 | /**
35 | * Indicate that the model's email address should be unverified.
36 | *
37 | * @return \Illuminate\Database\Eloquent\Factories\Factory
38 | */
39 | public function unverified()
40 | {
41 | return $this->state(function (array $attributes) {
42 | return [
43 | 'email_verified_at' => null,
44 | ];
45 | });
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/app/Mail/UserInAdminCreated.php:
--------------------------------------------------------------------------------
1 | user = $user;
38 | $this->password = $password;
39 | }
40 |
41 | /**
42 | * Build the message.
43 | *
44 | * @return $this
45 | */
46 | public function build()
47 | {
48 | return $this->markdown('emails.user.created')
49 | ->with([
50 | 'user' => $this->user,
51 | 'password' => $this->password,
52 | 'url' => URL::route('admin.dashboard')
53 | ]);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/database/migrations/2021_05_17_130359_create_answers_table.php:
--------------------------------------------------------------------------------
1 | id();
18 |
19 | $table->unsignedBigInteger('electionparty_id');
20 | $table->foreign('electionparty_id')
21 | ->references('id')->on('election_party')
22 | ->onDelete('cascade');
23 |
24 | $table->unsignedBigInteger('question_id');
25 | $table->foreign('question_id')
26 | ->references('id')->on('questions')
27 | ->onDelete('cascade');
28 |
29 | $table->unique(['electionparty_id', 'question_id']);
30 |
31 | $table->integer('answer')->default(0);
32 | $table->json('reason')->nullable();
33 |
34 | $table->timestamps();
35 | });
36 | }
37 |
38 | /**
39 | * Reverse the migrations.
40 | *
41 | * @return void
42 | */
43 | public function down()
44 | {
45 | Schema::dropIfExists('answers');
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/public/js/app.js.LICENSE.txt:
--------------------------------------------------------------------------------
1 | /*
2 | object-assign
3 | (c) Sindre Sorhus
4 | @license MIT
5 | */
6 |
7 | /* NProgress, (c) 2013, 2014 Rico Sta. Cruz - http://ricostacruz.com/nprogress
8 | * @license MIT */
9 |
10 | /*!
11 | Copyright (c) 2018 Jed Watson.
12 | Licensed under the MIT License (MIT), see
13 | http://jedwatson.github.io/classnames
14 | */
15 |
16 | /**
17 | * @license @tabler/icons-react v3.3.0 - MIT
18 | *
19 | * This source code is licensed under the MIT license.
20 | * See the LICENSE file in the root directory of this source tree.
21 | */
22 |
23 | /** @license React v0.20.2
24 | * scheduler.production.min.js
25 | *
26 | * Copyright (c) Facebook, Inc. and its affiliates.
27 | *
28 | * This source code is licensed under the MIT license found in the
29 | * LICENSE file in the root directory of this source tree.
30 | */
31 |
32 | /** @license React v17.0.2
33 | * react-dom.production.min.js
34 | *
35 | * Copyright (c) Facebook, Inc. and its affiliates.
36 | *
37 | * This source code is licensed under the MIT license found in the
38 | * LICENSE file in the root directory of this source tree.
39 | */
40 |
41 | /** @license React v17.0.2
42 | * react.production.min.js
43 | *
44 | * Copyright (c) Facebook, Inc. and its affiliates.
45 | *
46 | * This source code is licensed under the MIT license found in the
47 | * LICENSE file in the root directory of this source tree.
48 | */
49 |
--------------------------------------------------------------------------------
/database/migrations/2021_07_30_183603_add_locale_to_analytics_tables.php:
--------------------------------------------------------------------------------
1 | string('locale')->nullable();
18 | });
19 |
20 | Schema::table('initiations', function (Blueprint $table) {
21 | $table->string('locale')->nullable();
22 | });
23 |
24 | Schema::table('results', function (Blueprint $table) {
25 | $table->string('locale')->nullable();
26 | });
27 | }
28 |
29 | /**
30 | * Reverse the migrations.
31 | *
32 | * @return void
33 | */
34 | public function down()
35 | {
36 | Schema::table('results', function (Blueprint $table) {
37 | $table->dropColumn('locale');
38 | });
39 |
40 | Schema::table('initiations', function (Blueprint $table) {
41 | $table->dropColumn('locale');
42 | });
43 |
44 | Schema::table('swipes', function (Blueprint $table) {
45 | $table->string('locale')->nullable();
46 | });
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/resources/js/config/locales.ts:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { FlagDE } from '../components/flags/de';
3 | import { FlagFI } from '../components/flags/fi';
4 | import { FlagFR } from '../components/flags/fr';
5 | import { FlagSV } from '../components/flags/sv';
6 | import { FlagUS } from '../components/flags/us';
7 |
8 | const locales: {
9 | [key: string]: {
10 | label: string;
11 | flag: React.FC>;
12 | };
13 | } = {
14 | de: {
15 | label: 'German',
16 | flag: FlagDE,
17 | },
18 | fi: {
19 | label: 'Finnish',
20 | flag: FlagFI,
21 | },
22 | fr: {
23 | label: 'French',
24 | flag: FlagFR,
25 | },
26 | sv: {
27 | label: 'Swedish',
28 | flag: FlagSV,
29 | },
30 | en: {
31 | label: 'English',
32 | flag: FlagUS,
33 | },
34 | it: {
35 | label: 'Italian',
36 | flag: FlagUS,
37 | },
38 | ru: {
39 | label: 'Russian',
40 | flag: FlagUS,
41 | },
42 | fa: {
43 | label: 'Farsi',
44 | flag: FlagUS,
45 | },
46 | ar: {
47 | label: 'Arabic',
48 | flag: FlagUS,
49 | },
50 | tr: {
51 | label: 'Turkish',
52 | flag: FlagUS,
53 | },
54 | ku: {
55 | label: 'Kurdish',
56 | flag: FlagUS,
57 | },
58 | };
59 |
60 | export default locales;
61 |
--------------------------------------------------------------------------------
/app/Http/Requests/CreateOrEditElection.php:
--------------------------------------------------------------------------------
1 | 'integer|required|exists:countries,id',
29 | 'published' => 'boolean|required',
30 | 'playable' => 'boolean|required',
31 | 'name' => 'string|required',
32 | 'voting_day' => 'string|date|required',
33 | 'playable_date' => 'string|date|required',
34 | 'translations_available' => 'array|required',
35 | ];
36 |
37 | if ($this->election) {
38 | $rules['card'] = 'image|nullable|max:1024|mimes:jpeg,png,gif';
39 | $rules['card_upload_id'] = 'integer|required|exists:uploads,id';
40 | } else {
41 | $rules['card'] = 'image|required|max:1024|mimes:jpeg,png,gif';
42 | }
43 |
44 | return $rules;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Admin/StatisticController.php:
--------------------------------------------------------------------------------
1 | get();
18 | $swipes = Swipe::count();
19 | $initiations = Initiation::count();
20 | $results = Result::count();
21 |
22 | return Inertia::render('statistic', [
23 | 'elections' => $elections,
24 | 'swipes' => $swipes,
25 | 'initiations' => $initiations,
26 | 'results' => $results,
27 | ]);
28 | }
29 |
30 | public function election(Election $election)
31 | {
32 | $swipes = Swipe::where('election_id', $election->id)->count();
33 | $initiations = Initiation::where('election_id', $election->id)->count();
34 | $results = Result::where('election_id', $election->id)->count();
35 |
36 | return Inertia::render('statistic/election', [
37 | 'election' => $election,
38 | 'swipes' => $swipes,
39 | 'initiations' => $initiations,
40 | 'results' => $results,
41 | ]);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/database/migrations/2021_05_16_175828_create_questions_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->timestamps();
19 | $table->unsignedBigInteger('election_id');
20 | $table->foreign('election_id')
21 | ->references('id')->on('elections')
22 | ->onDelete('cascade');
23 | $table->json('thesis');
24 | $table->json('topic')->nullable();
25 | $table->json('video_url')->nullable();
26 | $table->json('explainer_text')->nullable();
27 | $table->unsignedBigInteger('thumbnail_upload_id')->nullable();
28 | $table->foreign('thumbnail_upload_id')
29 | ->references('id')->on('uploads')
30 | ->onDelete('set null');
31 | $table->integer('sort_order')->nullable();
32 | });
33 | }
34 |
35 | /**
36 | * Reverse the migrations.
37 | *
38 | * @return void
39 | */
40 | public function down()
41 | {
42 | Schema::dropIfExists('questions');
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/Http/Middleware/HandleInertiaRequests.php:
--------------------------------------------------------------------------------
1 | Session::get('success'),
43 | 'error' => Session::get('error'),
44 | 'locales' => config('app.locales'),
45 | 'locale' => App::currentLocale(),
46 | 'user' => auth()->user()
47 | ]);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/database/migrations/2021_05_15_105016_create_elections_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->timestamps();
19 | $table->foreignId('country_id')
20 | ->constrained()
21 | ->onUpdate('no action')
22 | ->onDelete('cascade');
23 | $table->json('name');
24 | $table->json('slug');
25 | $table->boolean('published')->default(false);
26 | $table->boolean('playable')->default(false);
27 | $table->unsignedBigInteger('card_upload_id')->nullable();
28 | $table->foreign('card_upload_id')
29 | ->references('id')->on('uploads')
30 | ->onDelete('set null');
31 |
32 | $table->date('voting_day');
33 | $table->dateTime('playable_date');
34 | $table->json('translations_available');
35 | });
36 | }
37 |
38 | /**
39 | * Reverse the migrations.
40 | *
41 | * @return void
42 | */
43 | public function down()
44 | {
45 | Schema::dropIfExists('elections');
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/app/Jobs/CountAnswer.php:
--------------------------------------------------------------------------------
1 | election_id = $election_id;
31 | $this->question_id = $question_id;
32 | $this->answer = $answer;
33 | $this->platform = $platform;
34 | $this->locale = $locale;
35 | }
36 |
37 | /**
38 | * Execute the job.
39 | *
40 | * @return void
41 | */
42 | public function handle()
43 | {
44 | Swipe::create([
45 | 'election_id' => $this->election_id,
46 | 'question_id' => $this->question_id,
47 | 'answer' => $this->answer,
48 | 'platform' => $this->platform,
49 | 'locale' => $this->locale
50 | ]);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/Jobs/SaveResult.php:
--------------------------------------------------------------------------------
1 | election_id = $election_id;
31 | $this->result = json_decode($result);
32 | $this->party_id = $party_id;
33 | $this->platform = $platform;
34 | $this->locale = $locale;
35 | }
36 |
37 | /**
38 | * Execute the job.
39 | *
40 | * @return void
41 | */
42 | public function handle()
43 | {
44 | Result::create([
45 | 'election_id' => $this->election_id,
46 | 'result' => $this->result,
47 | 'party_id' => $this->party_id,
48 | 'platform' => $this->platform,
49 | 'locale' => $this->locale,
50 | ]);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/database/migrations/2021_05_16_213233_create_election_parties_pivot.php:
--------------------------------------------------------------------------------
1 | id();
18 |
19 | $table->unsignedBigInteger('election_id');
20 | $table->foreign('election_id')
21 | ->references('id')->on('elections')
22 | ->onDelete('cascade');
23 |
24 | $table->unsignedBigInteger('party_id');
25 | $table->foreign('party_id')
26 | ->references('id')->on('parties')
27 | ->onDelete('cascade');
28 |
29 | $table->boolean('playable')->default(false);
30 | $table->boolean('published')->default(false);
31 |
32 | $table->unsignedBigInteger('program_upload_id')->nullable();
33 | $table->foreign('program_upload_id')
34 | ->references('id')->on('uploads')
35 | ->onDelete('set null');
36 |
37 | $table->string('program_link')->nullable();
38 |
39 | $table->timestamps();
40 | });
41 | }
42 |
43 | /**
44 | * Reverse the migrations.
45 | *
46 | * @return void
47 | */
48 | public function down()
49 | {
50 | Schema::dropIfExists('election_party');
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/Models/Question.php:
--------------------------------------------------------------------------------
1 | belongsTo(Election::class);
49 | }
50 |
51 | /**
52 | * Get the uploaded file
53 | */
54 | public function thumbnail(): BelongsTo
55 | {
56 | return $this->belongsTo(Upload::class, 'thumbnail_upload_id', 'id');
57 | }
58 |
59 | /**
60 | * Sort query based on election
61 | */
62 | public function buildSortQuery()
63 | {
64 | return static::query()->where('election_id', $this->election_id);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/app/Models/Party.php:
--------------------------------------------------------------------------------
1 | generateSlugsFrom('name')
37 | ->saveSlugsTo('slug');
38 | }
39 |
40 | /**
41 | * Get the country
42 | */
43 | public function country(): BelongsTo
44 | {
45 | return $this->belongsTo(Country::class);
46 | }
47 |
48 | /**
49 | * Get the uploaded file
50 | */
51 | public function logo(): BelongsTo
52 | {
53 | return $this->belongsTo(Upload::class, 'logo_upload_id', 'id');
54 | }
55 |
56 | public function elections(): BelongsToMany
57 | {
58 | return $this->belongsToMany(Election::class)->using(ElectionParty::class)
59 | ->withPivot('playable', 'published', 'program_upload_id', 'program_link', 'id')
60 | ->withTimestamps();
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/app/Http/Middleware/LocalizeApi.php:
--------------------------------------------------------------------------------
1 | app = $app;
19 | }
20 |
21 | /**
22 | * Handle an incoming request.
23 | *
24 | * @param \Illuminate\Http\Request $request
25 | * @param \Closure $next
26 | * @return mixed
27 | */
28 | public function handle(Request $request, Closure $next)
29 | {
30 | // read the language from the request header
31 | $locale = $request->header('Content-Language');
32 |
33 | // if the header is missed
34 | if (!$locale) {
35 | // take the default local language
36 | $locale = $this->app->config->get('app.locale');
37 | }
38 |
39 | // check the languages defined is supported
40 | if (!in_array($locale, $this->app->config->get('app.locales'))) {
41 | // respond with error
42 | return abort(403, 'Language not supported.');
43 | }
44 |
45 | // set the local language
46 | $this->app->setLocale($locale);
47 |
48 | // get the response after the request is done
49 | $response = $next($request);
50 |
51 | // set Content Languages header in the response
52 | $response->headers->set('Content-Language', $locale);
53 |
54 | // return the response
55 | return $response;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/routes/api.php:
--------------------------------------------------------------------------------
1 | version('v1', function ($api) {
23 | $api->post('countries', [CountryController::class, 'index']);
24 | $api->post('alternateCountrySlugs', [CountryController::class, 'alternateCountrySlugs']);
25 | $api->post('countryBySlug', [CountryController::class, 'countryBySlug']);
26 |
27 | $api->post('elections', [ElectionController::class, 'index']);
28 | $api->post('election', [ElectionController::class, 'election']);
29 | $api->post('alternateElectionSlugs', [ElectionController::class, 'alternateElectionSlugs']);
30 |
31 | $api->post('parties', [PartyController::class, 'index']);
32 |
33 | $api->post('questions', [QuestionController::class, 'index']);
34 |
35 | $api->post('/statistics/countAnswer', [StatisticController::class, 'countAnswer']);
36 | $api->post('/statistics/initiate', [StatisticController::class, 'initiate']);
37 | $api->post('/statistics/saveResult', [StatisticController::class, 'saveResult']);
38 | });
39 |
--------------------------------------------------------------------------------
/app/Models/Country.php:
--------------------------------------------------------------------------------
1 | generateSlugsFrom('name')
46 | ->saveSlugsTo('slug');
47 | }
48 |
49 | /**
50 | * The attributes that should be cast.
51 | *
52 | * @var array
53 | */
54 | protected $casts = [
55 | 'published' => 'boolean',
56 | ];
57 |
58 | /**
59 | * Get the parties for this country
60 | */
61 | public function parties(): HasMany
62 | {
63 | return $this->hasMany(Party::class);
64 | }
65 |
66 | /**
67 | * Elections
68 | */
69 | public function elections(): HasMany
70 | {
71 | return $this->hasMany(Election::class);
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/config/hashing.php:
--------------------------------------------------------------------------------
1 | 'bcrypt',
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Bcrypt Options
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may specify the configuration options that should be used when
26 | | passwords are hashed using the Bcrypt algorithm. This will allow you
27 | | to control the amount of time it takes to hash the given password.
28 | |
29 | */
30 |
31 | 'bcrypt' => [
32 | 'rounds' => env('BCRYPT_ROUNDS', 10),
33 | ],
34 |
35 | /*
36 | |--------------------------------------------------------------------------
37 | | Argon Options
38 | |--------------------------------------------------------------------------
39 | |
40 | | Here you may specify the configuration options that should be used when
41 | | passwords are hashed using the Argon algorithm. These will allow you
42 | | to control the amount of time it takes to hash the given password.
43 | |
44 | */
45 |
46 | 'argon' => [
47 | 'memory' => 1024,
48 | 'threads' => 2,
49 | 'time' => 2,
50 | ],
51 |
52 | ];
53 |
--------------------------------------------------------------------------------
/bootstrap/app.php:
--------------------------------------------------------------------------------
1 | singleton(
30 | Illuminate\Contracts\Http\Kernel::class,
31 | App\Http\Kernel::class
32 | );
33 |
34 | $app->singleton(
35 | Illuminate\Contracts\Console\Kernel::class,
36 | App\Console\Kernel::class
37 | );
38 |
39 | $app->singleton(
40 | Illuminate\Contracts\Debug\ExceptionHandler::class,
41 | App\Exceptions\Handler::class
42 | );
43 |
44 | /*
45 | |--------------------------------------------------------------------------
46 | | Return The Application
47 | |--------------------------------------------------------------------------
48 | |
49 | | This script returns the application instance. The instance is given to
50 | | the calling script so we can separate the building of the instances
51 | | from the actual running of the application and sending responses.
52 | |
53 | */
54 |
55 | return $app;
56 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # VoteSwiper / WahlSwiper - Website
2 |
3 | [](https://github.com/MOVACT/voteswiper-api/commits) [](https://github.com/MOVACT/voteswiper-api/issues) [](https://www.twitter.com/wahlswiper)
4 |
5 | VoteSwiper (in Germany better known as WahlSwiper) is a cross-platform voting advice app for Android, iOS and web browsers. The app is operated by [MOVACT](https://www.movact.de) primarily for German federale and state elections. The content for the surveys is researched and developed by various institutions, most recently mainly by political scientists at the University of Freiburg.
6 |
7 | We started this project in 2017 for the federal election and since then grow a user base of over one million. While we operated closed source for a long time, we believe the right thing to do is to disclose the source code of the whole project for transparency.
8 |
9 | ## Development
10 |
11 | The API is built with Laravel & Inertia. The easiest way to start the project is to use Laravel Sail. Head over to the Laravel documentation [here](https://laravel.com/docs/8.x/sail) to learn more.
12 |
13 | ```console
14 | sail up
15 | ```
16 |
17 | ## How to contribute
18 |
19 | We appreciate any feedback. Feel free to open an issue if you find errors or use the discussion board if you'd like to suggest new features.
20 |
21 | ## Security Bugs
22 |
23 | If you find any security related issues we would appreciate if you safely disclose the issue to us via email to [max@voteswiper.org](mailto:max@voteswiper.org) directly.
24 |
25 | ## Contributors
26 |
27 | [](https://github.com/mxmtsk)
28 |
29 | ## License
30 |
31 | Copyright MOVACT GmbH
32 |
--------------------------------------------------------------------------------
/artisan:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env php
2 | make(Illuminate\Contracts\Console\Kernel::class);
34 |
35 | $status = $kernel->handle(
36 | $input = new Symfony\Component\Console\Input\ArgvInput,
37 | new Symfony\Component\Console\Output\ConsoleOutput
38 | );
39 |
40 | /*
41 | |--------------------------------------------------------------------------
42 | | Shutdown The Application
43 | |--------------------------------------------------------------------------
44 | |
45 | | Once Artisan has finished running, we will fire off the shutdown events
46 | | so that any final work may be done by the application before we shut
47 | | down the process. This is the last thing to happen to the request.
48 | |
49 | */
50 |
51 | $kernel->terminate($input, $status);
52 |
53 | exit($status);
54 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "scripts": {
4 | "dev": "npm run development",
5 | "development": "mix",
6 | "watch": "mix watch",
7 | "watch-poll": "mix watch -- --watch-options-poll=1000",
8 | "hot": "mix watch --hot",
9 | "prod": "npm run production",
10 | "production": "mix --production"
11 | },
12 | "devDependencies": {
13 | "@types/react": "^17.0.2",
14 | "@types/react-datepicker": "^3.1.8",
15 | "@types/react-dom": "^17.0.1",
16 | "@types/react-helmet": "^6.1.0",
17 | "@types/ziggy-js": "^1.8.0",
18 | "@typescript-eslint/eslint-plugin": "^4.15.2",
19 | "@typescript-eslint/parser": "^4.15.2",
20 | "axios": "^0.21",
21 | "eslint": "^7.20.0",
22 | "eslint-config-prettier": "^8.1.0",
23 | "eslint-plugin-jsx-a11y": "^6.4.1",
24 | "eslint-plugin-prettier": "^3.3.1",
25 | "eslint-plugin-react": "^7.22.0",
26 | "eslint-plugin-react-hooks": "^4.2.0",
27 | "laravel-mix": "^6.0.6",
28 | "lodash": "^4.17.19",
29 | "postcss": "^8.1.14",
30 | "prettier": "^2.2.1",
31 | "ts-loader": "^8.0.17",
32 | "typescript": "^4.2.2"
33 | },
34 | "dependencies": {
35 | "@inertiajs/inertia": "^0.8.5",
36 | "@inertiajs/inertia-react": "^0.5.4",
37 | "@inertiajs/progress": "^0.2.4",
38 | "@tabler/core": "^1.0.0-beta2",
39 | "@tabler/icons-react": "^3.3.0",
40 | "@types/classnames": "^2.3.1",
41 | "classnames": "^2.3.1",
42 | "date-fns": "^2.21.3",
43 | "prettier-plugin-organize-imports": "^2.0.0",
44 | "react": "^17.0.1",
45 | "react-datepicker": "^3.8.0",
46 | "react-dom": "^17.0.1",
47 | "react-helmet": "^6.1.0",
48 | "react-use": "^17.2.4",
49 | "ziggy-js": "^2.1.0"
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/Actions/Fortify/UpdateUserProfileInformation.php:
--------------------------------------------------------------------------------
1 | ['required', 'string', 'max:255'],
23 |
24 | 'email' => [
25 | 'required',
26 | 'string',
27 | 'email',
28 | 'max:255',
29 | Rule::unique('users')->ignore($user->id),
30 | ],
31 | ])->validateWithBag('updateProfileInformation');
32 |
33 | if ($input['email'] !== $user->email &&
34 | $user instanceof MustVerifyEmail) {
35 | $this->updateVerifiedUser($user, $input);
36 | } else {
37 | $user->forceFill([
38 | 'name' => $input['name'],
39 | 'email' => $input['email'],
40 | ])->save();
41 | }
42 | }
43 |
44 | /**
45 | * Update the given verified user's profile information.
46 | *
47 | * @param mixed $user
48 | * @param array $input
49 | * @return void
50 | */
51 | protected function updateVerifiedUser($user, array $input)
52 | {
53 | $user->forceFill([
54 | 'name' => $input['name'],
55 | 'email' => $input['email'],
56 | 'email_verified_at' => null,
57 | ])->save();
58 |
59 | $user->sendEmailVerificationNotification();
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/public/index.php:
--------------------------------------------------------------------------------
1 | make(Kernel::class);
50 |
51 | $response = tap($kernel->handle(
52 | $request = Request::capture()
53 | ))->send();
54 |
55 | $kernel->terminate($request, $response);
56 |
--------------------------------------------------------------------------------
/app/Providers/RouteServiceProvider.php:
--------------------------------------------------------------------------------
1 | configureRateLimiting();
39 |
40 | $this->routes(function () {
41 | Route::middleware('api')
42 | ->namespace($this->namespace)
43 | ->group(base_path('routes/api.php'));
44 |
45 | Route::prefix('admin')
46 | ->middleware('web')
47 | ->namespace($this->namespace)
48 | ->group(base_path('routes/web.php'));
49 | });
50 | }
51 |
52 | /**
53 | * Configure the rate limiters for the application.
54 | *
55 | * @return void
56 | */
57 | protected function configureRateLimiting()
58 | {
59 | RateLimiter::for('api', function (Request $request) {
60 | return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
61 | });
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/resources/js/components/page.tsx:
--------------------------------------------------------------------------------
1 | import { Page as InertiaPage } from '@inertiajs/inertia';
2 | import { usePage } from '@inertiajs/inertia-react';
3 | import React from 'react';
4 |
5 | interface Props {
6 | title: string | React.ReactElement;
7 | actions?: React.ReactElement;
8 | }
9 |
10 | interface PageProps {
11 | success?: string;
12 | error?: string;
13 | }
14 |
15 | export const Page: React.FC = ({ children, title, actions }) => {
16 | const { props } = usePage>();
17 | const { success, error } = props;
18 |
19 | return (
20 | <>
21 |
22 |
23 |
24 |
25 |
{title}
26 |
27 |
28 | {actions}
29 |
30 |
31 |
32 |
33 |
34 |
35 | {(success || error) && (
36 |
37 | {success && (
38 |
39 | {success}
40 |
41 | )}
42 |
43 | {error && (
44 |
45 | {error}
46 |
47 | )}
48 |
49 | )}
50 |
{children}
51 |
52 | >
53 | );
54 | };
55 |
--------------------------------------------------------------------------------
/app/Providers/FortifyServiceProvider.php:
--------------------------------------------------------------------------------
1 | by($request->email.$request->ip());
42 | });
43 |
44 | RateLimiter::for('two-factor', function (Request $request) {
45 | return Limit::perMinute(5)->by($request->session()->get('login.id'));
46 | });
47 |
48 | Fortify::loginView(fn () => Inertia::render('auth/login'));
49 | Fortify::requestPasswordResetLinkView(fn () => Inertia::render('auth/forgot-password'));
50 | Fortify::resetPasswordView(fn (Request $request) => Inertia::render('auth/reset-password', [
51 | "email" => $request->query('email'),
52 | "token" => $request->route()->parameter('token')
53 | ]));
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/config/broadcasting.php:
--------------------------------------------------------------------------------
1 | env('BROADCAST_DRIVER', 'null'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Broadcast Connections
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the broadcast connections that will be used
26 | | to broadcast events to other systems or over websockets. Samples of
27 | | each available type of connection are provided inside this array.
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'pusher' => [
34 | 'driver' => 'pusher',
35 | 'key' => env('PUSHER_APP_KEY'),
36 | 'secret' => env('PUSHER_APP_SECRET'),
37 | 'app_id' => env('PUSHER_APP_ID'),
38 | 'options' => [
39 | 'cluster' => env('PUSHER_APP_CLUSTER'),
40 | 'useTLS' => true,
41 | ],
42 | ],
43 |
44 | 'ably' => [
45 | 'driver' => 'ably',
46 | 'key' => env('ABLY_KEY'),
47 | ],
48 |
49 | 'redis' => [
50 | 'driver' => 'redis',
51 | 'connection' => 'default',
52 | ],
53 |
54 | 'log' => [
55 | 'driver' => 'log',
56 | ],
57 |
58 | 'null' => [
59 | 'driver' => 'null',
60 | ],
61 |
62 | ],
63 |
64 | ];
65 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Api/V1/StatisticController.php:
--------------------------------------------------------------------------------
1 | input('election_id'),
25 | $request->input('question_id'),
26 | $request->input('answer'),
27 | $request->input('platform'),
28 | App::getLocale(),
29 | );
30 |
31 | return ['status' => 'ok'];
32 | }
33 |
34 | /**
35 | * Initiate
36 | *
37 | * @Post("/statistics/initiate")
38 | * @Versions({"v1"})
39 | * @Request({}, headers={"Content-Language": "en"})
40 | */
41 | public function initiate(Request $request)
42 | {
43 | InitiateSwiper::dispatch(
44 | $request->input('election_id'),
45 | $request->input('platform'),
46 | App::getLocale(),
47 | );
48 |
49 | return ['status' => 'ok'];
50 | }
51 |
52 | /**
53 | * Save Result
54 | *
55 | * @Post("/statistics/initiate")
56 | * @Versions({"v1"})
57 | * @Request({}, headers={"Content-Language": "en"})
58 | */
59 | public function saveResult(Request $request)
60 | {
61 | SaveResult::dispatch(
62 | $request->input('election_id'),
63 | $request->input('result'),
64 | $request->input('top_party_id'),
65 | $request->input('platform'),
66 | App::getLocale(),
67 | );
68 |
69 | return ['status' => 'ok'];
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | # For more information: https://laravel.com/docs/sail
2 | version: '3'
3 | services:
4 | laravel.test:
5 | build:
6 | context: ./vendor/laravel/sail/runtimes/8.0
7 | dockerfile: Dockerfile
8 | args:
9 | WWWGROUP: '${WWWGROUP}'
10 | image: sail-8.0/app
11 | ports:
12 | - '${APP_PORT:-80}:80'
13 | environment:
14 | WWWUSER: '${WWWUSER}'
15 | LARAVEL_SAIL: 1
16 | volumes:
17 | - '.:/var/www/html'
18 | networks:
19 | - sail
20 | depends_on:
21 | - mysql
22 | - redis
23 | - selenium
24 | mysql:
25 | image: 'mysql:8.0'
26 | ports:
27 | - '${FORWARD_DB_PORT:-3306}:3306'
28 | environment:
29 | MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
30 | MYSQL_DATABASE: '${DB_DATABASE}'
31 | MYSQL_USER: '${DB_USERNAME}'
32 | MYSQL_PASSWORD: '${DB_PASSWORD}'
33 | MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
34 | volumes:
35 | - 'sailmysql:/var/lib/mysql'
36 | networks:
37 | - sail
38 | healthcheck:
39 | test: ["CMD", "mysqladmin", "ping"]
40 | redis:
41 | image: 'redis:alpine'
42 | ports:
43 | - '${FORWARD_REDIS_PORT:-6379}:6379'
44 | volumes:
45 | - 'sailredis:/data'
46 | networks:
47 | - sail
48 | healthcheck:
49 | test: ["CMD", "redis-cli", "ping"]
50 | selenium:
51 | image: 'selenium/standalone-chrome'
52 | volumes:
53 | - '/dev/shm:/dev/shm'
54 | networks:
55 | - sail
56 | mailhog:
57 | image: 'mailhog/mailhog:latest'
58 | ports:
59 | - '${FORWARD_MAILHOG_PORT:-1025}:1025'
60 | - '${FORWARD_MAILHOG_DASHBOARD_PORT:-8025}:8025'
61 | networks:
62 | - sail
63 | networks:
64 | sail:
65 | driver: bridge
66 | volumes:
67 | sailmysql:
68 | driver: local
69 | sailredis:
70 | driver: local
71 |
--------------------------------------------------------------------------------
/resources/js/components/locale-switch.tsx:
--------------------------------------------------------------------------------
1 | import { Page } from '@inertiajs/inertia';
2 | import { usePage } from '@inertiajs/inertia-react';
3 | import { IconLanguage } from '@tabler/icons-react';
4 | import cn from 'classnames';
5 | import React from 'react';
6 | import { useClickAway } from 'react-use';
7 | import { route } from 'ziggy-js';
8 | import localeStrings from '../config/locales';
9 |
10 | interface Props {
11 | locales: string[];
12 | }
13 |
14 | export const LocaleSwitch: React.FC = ({ locales }) => {
15 | const $dropdownEl = React.useRef(null);
16 | const { props } = usePage>();
17 | const [open, setOpen] = React.useState(false);
18 | useClickAway($dropdownEl, () => {
19 | setOpen(false);
20 | });
21 | const currentLocale = props.locale;
22 |
23 | return (
24 | <>
25 |
26 |
36 |
55 |
56 | >
57 | );
58 | };
59 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "laravel/laravel",
3 | "type": "project",
4 | "description": "The Laravel Framework.",
5 | "keywords": [
6 | "framework",
7 | "laravel"
8 | ],
9 | "license": "MIT",
10 | "require": {
11 | "php": "^7.3|^8.0",
12 | "dingo/api": "dev-master",
13 | "fideloper/proxy": "^4.4",
14 | "fruitcake/laravel-cors": "^2.0",
15 | "guzzlehttp/guzzle": "^7.0.1",
16 | "inertiajs/inertia-laravel": "^0.3.6",
17 | "laravel/fortify": "^1.7",
18 | "laravel/framework": "^8.12",
19 | "laravel/tinker": "^2.5",
20 | "league/flysystem-aws-s3-v3": "~1.0",
21 | "spatie/eloquent-sortable": "^4.0",
22 | "spatie/laravel-sluggable": "^2.6",
23 | "spatie/laravel-translatable": "^4.6",
24 | "tightenco/ziggy": "^1.0"
25 | },
26 | "require-dev": {
27 | "facade/ignition": "^2.5",
28 | "fakerphp/faker": "^1.9.1",
29 | "laravel/sail": "^1.0.1",
30 | "mockery/mockery": "^1.4.2",
31 | "nunomaduro/collision": "^5.0",
32 | "phpunit/phpunit": "^9.3.3"
33 | },
34 | "config": {
35 | "optimize-autoloader": true,
36 | "preferred-install": "dist",
37 | "sort-packages": true
38 | },
39 | "extra": {
40 | "laravel": {
41 | "dont-discover": []
42 | }
43 | },
44 | "autoload": {
45 | "psr-4": {
46 | "App\\": "app/",
47 | "Database\\Factories\\": "database/factories/",
48 | "Database\\Seeders\\": "database/seeders/"
49 | }
50 | },
51 | "autoload-dev": {
52 | "psr-4": {
53 | "Tests\\": "tests/"
54 | }
55 | },
56 | "minimum-stability": "dev",
57 | "prefer-stable": true,
58 | "scripts": {
59 | "post-autoload-dump": [
60 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
61 | "@php artisan package:discover --ansi"
62 | ],
63 | "post-root-package-install": [
64 | "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
65 | ],
66 | "post-create-project-cmd": [
67 | "@php artisan key:generate --ansi"
68 | ]
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: {
4 | node: true,
5 | es6: true,
6 | },
7 | parserOptions: { ecmaVersion: 8 }, // to enable features such as async/await
8 | ignorePatterns: ['node_modules/*', '!.prettierrc.js'], // We don't want to lint generated files nor node_modules, but we want to lint .prettierrc.js (ignored by default by eslint)
9 | extends: ['eslint:recommended'],
10 | overrides: [
11 | // This configuration will apply only to TypeScript files
12 | {
13 | files: ['resources/js/**/*.ts', 'resources/js/**/*.tsx'],
14 | parser: '@typescript-eslint/parser',
15 | settings: { react: { version: 'detect' } },
16 | env: {
17 | browser: true,
18 | node: true,
19 | es6: true,
20 | },
21 | extends: [
22 | 'eslint:recommended',
23 | 'plugin:@typescript-eslint/recommended', // TypeScript rules
24 | 'plugin:react/recommended', // React rules
25 | 'plugin:react-hooks/recommended', // React hooks rules
26 | 'plugin:jsx-a11y/recommended', // Accessibility rules
27 | 'plugin:prettier/recommended', // Prettier recommended rules
28 | ],
29 | rules: {
30 | // We will use TypeScript's types for component props instead
31 | 'react/prop-types': 'off',
32 |
33 | 'react/display-name': 'off',
34 |
35 | // No need to import React when using Next.js
36 | 'react/react-in-jsx-scope': 'off',
37 |
38 | // This rule is not compatible with Next.js's components
39 | 'jsx-a11y/anchor-is-valid': 'off',
40 |
41 | // Why would you want unused vars?
42 | '@typescript-eslint/no-unused-vars': ['error'],
43 |
44 | // I suggest this setting for requiring return types on functions only where useful
45 | '@typescript-eslint/explicit-function-return-type': [
46 | 'warn',
47 | {
48 | allowExpressions: true,
49 | allowConciseArrowFunctionExpressionsStartingWithVoid: true,
50 | },
51 | ],
52 |
53 | 'prettier/prettier': ['error', {}, { usePrettierrc: true }],
54 | },
55 | },
56 | ],
57 | }
58 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Api/V1/QuestionController.php:
--------------------------------------------------------------------------------
1 | header('API-Preview-Key', 'default') === env('API_PREVIEW_KEY');
26 |
27 | if (!$request->input('slug') && !$request->input('id')) {
28 | throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException('No election slug or id was provided.');
29 | }
30 |
31 | $currentLocale = App::getLocale();
32 | $value = $request->input('id') ?? $request->input('slug');
33 |
34 | $cacheKey = $currentLocale . '_questions_' . $value;
35 |
36 | if (!Cache::has($cacheKey) || $isPreview) {
37 | if ($request->input('id')) {
38 | $election = Election::where('id', $request->input('id'));
39 | } else {
40 | $election = Election::where(function($query) use($request, $currentLocale) {
41 | $query->where('slug->' . $currentLocale, $request->input('slug'))->orWhere('slug->en', $request->input('slug'));
42 | });
43 | }
44 |
45 | if ($isPreview) {
46 | $election = $election->firstOrFail();
47 | } else {
48 | $election = $election->where('published', true)->where('playable', true)->firstOrFail();
49 | Cache::put($cacheKey, $election->questions()->ordered()->with('thumbnail')->get(), now()->addMinutes(120));
50 | }
51 |
52 | }
53 |
54 | if ($isPreview) {
55 | return $election->questions()->ordered()->with('thumbnail')->get();
56 | }
57 |
58 | return Cache::get($cacheKey);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/database/migrations/2021_05_31_202541_create_statistics_table.php:
--------------------------------------------------------------------------------
1 | id();
18 | $table->unsignedBigInteger('question_id');
19 | $table->foreign('question_id')
20 | ->references('id')->on('questions')
21 | ->onDelete('cascade');
22 |
23 | $table->unsignedBigInteger('election_id');
24 | $table->foreign('election_id')
25 | ->references('id')->on('elections')
26 | ->onDelete('cascade');
27 |
28 | $table->integer('answer');
29 | $table->string('platform');
30 | $table->timestamps();
31 | });
32 |
33 | Schema::create('initiations', function (Blueprint $table) {
34 | $table->id();
35 |
36 | $table->unsignedBigInteger('election_id');
37 | $table->foreign('election_id')
38 | ->references('id')->on('elections')
39 | ->onDelete('cascade');
40 |
41 | $table->string('platform');
42 | $table->timestamps();
43 | });
44 |
45 | Schema::create('results', function (Blueprint $table) {
46 | $table->id();
47 |
48 | $table->unsignedBigInteger('election_id');
49 | $table->foreign('election_id')
50 | ->references('id')->on('elections')
51 | ->onDelete('cascade');
52 |
53 | $table->unsignedBigInteger('party_id');
54 | $table->foreign('party_id')
55 | ->references('id')->on('parties')
56 | ->onDelete('cascade');
57 |
58 | $table->json('result');
59 | $table->string('platform');
60 | $table->timestamps();
61 | });
62 | }
63 |
64 | /**
65 | * Reverse the migrations.
66 | *
67 | * @return void
68 | */
69 | public function down()
70 | {
71 | Schema::dropIfExists('swipes');
72 | Schema::dropIfExists('initiations');
73 | Schema::dropIfExists('results');
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/resources/js/types.d.ts:
--------------------------------------------------------------------------------
1 | interface InertiaPage extends React.FC {
2 | layout?: (page: React.ReactChildren) => React.ReactElement;
3 | }
4 |
5 | interface User {
6 | id: number;
7 | name: string;
8 | email: string;
9 | }
10 |
11 | interface GlobalProps {
12 | locale: string;
13 | locales: string[];
14 | user: User;
15 | }
16 |
17 | interface TranslatedColumn {
18 | [locale: string]: string;
19 | }
20 |
21 | interface Country {
22 | id: number;
23 | name: string;
24 | country_code: string;
25 | language_code: string;
26 | published: boolean;
27 | slug: string;
28 | }
29 |
30 | interface CountryWithTranslations {
31 | id: number;
32 | name: TranslatedColumn;
33 | country_code: string;
34 | language_code: string;
35 | published: boolean;
36 | slug: TranslatedColumn;
37 | }
38 |
39 | interface Upload {
40 | id: number;
41 | filename: string;
42 | filesize: number;
43 | filetype: string;
44 | width: number | null;
45 | height: number | null;
46 | alt_text: string | null;
47 | }
48 |
49 | interface Answer {
50 | id: number;
51 | reason: string;
52 | answer: number;
53 | question_id: number;
54 | }
55 |
56 | interface ElectionPartyPivot {
57 | published: boolean;
58 | playable: boolean;
59 | program_upload_id: number;
60 | program_link: string;
61 | program: Upload;
62 | answers: Answer[];
63 | answers_count?: number;
64 | }
65 |
66 | interface Party {
67 | id: number;
68 | country_id: number;
69 | country: Country;
70 | name: string;
71 | slug: string;
72 | full_name: string;
73 | url: string | null;
74 | logo_upload_id: number;
75 | logo: Upload;
76 | pivot: ElectionPartyPivot;
77 | }
78 |
79 | interface Question {
80 | id: number;
81 | thesis: string;
82 | topic: string;
83 | video_url: string | null;
84 | explainer_text: string | null;
85 | thumbnail_upload_id: number;
86 | thumbnail: Upload;
87 | }
88 |
89 | interface Election {
90 | id: number;
91 | country_id: number;
92 | country: Country;
93 | name: string;
94 | followup_link: string;
95 | slug: string;
96 | card_upload_id: number;
97 | card: Upload;
98 | published: boolean;
99 | playable: boolean;
100 | voting_day: string;
101 | playable_date: string;
102 | translations_available: string[];
103 | questions_count?: number;
104 | parties_count?: number;
105 | }
106 |
107 | interface ElectionWithQuestions extends Election {
108 | questions: Question[];
109 | }
110 |
111 | interface ElectionWithParties extends Election {
112 | parties: Party[];
113 | }
114 |
--------------------------------------------------------------------------------
/app/Http/Kernel.php:
--------------------------------------------------------------------------------
1 | [
33 | \App\Http\Middleware\EncryptCookies::class,
34 | \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
35 | \Illuminate\Session\Middleware\StartSession::class,
36 | \App\Http\Middleware\SetLocale::class,
37 | // \Illuminate\Session\Middleware\AuthenticateSession::class,
38 | \Illuminate\View\Middleware\ShareErrorsFromSession::class,
39 | \App\Http\Middleware\VerifyCsrfToken::class,
40 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
41 | \App\Http\Middleware\HandleInertiaRequests::class,
42 | ],
43 |
44 | 'api' => [
45 | 'throttle:api',
46 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
47 | ],
48 | ];
49 |
50 | /**
51 | * The application's route middleware.
52 | *
53 | * These middleware may be assigned to groups or used individually.
54 | *
55 | * @var array
56 | */
57 | protected $routeMiddleware = [
58 | 'auth' => \App\Http\Middleware\Authenticate::class,
59 | 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
60 | 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
61 | 'can' => \Illuminate\Auth\Middleware\Authorize::class,
62 | 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
63 | 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
64 | 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
65 | 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
66 | 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
67 | ];
68 | }
69 |
--------------------------------------------------------------------------------
/config/filesystems.php:
--------------------------------------------------------------------------------
1 | env('FILESYSTEM_DRIVER', 'local'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Filesystem Disks
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure as many filesystem "disks" as you wish, and you
24 | | may even configure multiple disks of the same driver. Defaults have
25 | | been setup for each driver as an example of the required options.
26 | |
27 | | Supported Drivers: "local", "ftp", "sftp", "s3"
28 | |
29 | */
30 |
31 | 'disks' => [
32 |
33 | 'local' => [
34 | 'driver' => 'local',
35 | 'root' => storage_path('app'),
36 | ],
37 |
38 | 'public' => [
39 | 'driver' => 'local',
40 | 'root' => storage_path('app/public'),
41 | 'url' => env('APP_URL').'/storage',
42 | 'visibility' => 'public',
43 | ],
44 |
45 | 's3' => [
46 | 'driver' => 's3',
47 | 'key' => env('AWS_ACCESS_KEY_ID'),
48 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
49 | 'region' => env('AWS_DEFAULT_REGION'),
50 | 'bucket' => env('AWS_BUCKET'),
51 | 'url' => env('AWS_URL'),
52 | 'endpoint' => env('AWS_ENDPOINT'),
53 | ],
54 |
55 | 'spaces' => [
56 | 'driver' => 's3',
57 | 'key' => env('DO_SPACES_KEY'),
58 | 'secret' => env('DO_SPACES_SECRET'),
59 | 'endpoint' => env('DO_SPACES_ENDPOINT'),
60 | 'region' => env('DO_SPACES_REGION'),
61 | 'bucket' => env('DO_SPACES_BUCKET'),
62 | ],
63 |
64 | ],
65 |
66 | /*
67 | |--------------------------------------------------------------------------
68 | | Symbolic Links
69 | |--------------------------------------------------------------------------
70 | |
71 | | Here you may configure the symbolic links that will be created when the
72 | | `storage:link` Artisan command is executed. The array keys should be
73 | | the locations of the links and the values should be their targets.
74 | |
75 | */
76 |
77 | 'links' => [
78 | public_path('storage') => storage_path('app/public'),
79 | ],
80 |
81 | ];
82 |
--------------------------------------------------------------------------------
/resources/js/components/form/answer.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | interface Props
4 | extends React.DetailedHTMLProps<
5 | React.InputHTMLAttributes,
6 | HTMLInputElement
7 | > {
8 | label?: string;
9 | error: boolean;
10 | helperText?: string | React.ReactNode;
11 | }
12 |
13 | const Answer: React.FC = ({
14 | label,
15 | error,
16 | helperText,
17 | ...restProps
18 | }) => {
19 | return (
20 |
21 | {label &&
}
22 |
66 |
67 | );
68 | };
69 |
70 | export default Answer;
71 |
--------------------------------------------------------------------------------
/resources/js/components/form/translations.tsx:
--------------------------------------------------------------------------------
1 | import cn from 'classnames';
2 | import React from 'react';
3 | import locales from '../../config/locales';
4 |
5 | interface Props {
6 | label: string;
7 | error: boolean;
8 | disabled?: boolean;
9 | helperText?: string | React.ReactNode;
10 | value: string[];
11 | onChange: (translations: string[]) => void;
12 | }
13 |
14 | const Translations: React.FC = ({
15 | label,
16 | error,
17 | helperText,
18 | disabled = false,
19 | onChange,
20 | value,
21 | }) => {
22 | return (
23 |
24 | {label && }
25 | {Object.keys(locales).map((loc) => {
26 | return (
27 |
64 | );
65 | })}
66 | {helperText && (
67 |
68 | {helperText}
69 |
70 | )}
71 |
72 | );
73 | };
74 |
75 | export default Translations;
76 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Admin/UserController.php:
--------------------------------------------------------------------------------
1 | get(['id', 'name', 'email']);
30 |
31 | return Inertia::render('users', [
32 | 'users' => $users
33 | ]);
34 | }
35 |
36 | /**
37 | * Shows the form for creating a new user
38 | *
39 | * @return Response
40 | */
41 | public function create()
42 | {
43 | return Inertia::render('users/createOrEdit');
44 | }
45 |
46 | /**
47 | * Save new user
48 | *
49 | * @param CreateOrEditUser $request
50 | * @return RedirectResponse
51 | * @throws Exception
52 | * @throws BindingResolutionException
53 | * @throws RouteNotFoundException
54 | */
55 | public function store(CreateOrEditUser $request) {
56 | $password = Str::random(15);
57 | $passwordHash = Hash::make($password);
58 |
59 | $userData = $request->input();
60 | $userData['email_verified_at'] = Carbon::now();
61 | $userData['password'] = $passwordHash;
62 |
63 | $user = User::create($userData);
64 |
65 | if ($user) Mail::to($user->email)->send(new UserInAdminCreated($user, $password));
66 |
67 | return redirect()->route('admin.users')->with(['success' => 'The user was created successfully.']);
68 | }
69 |
70 | /**
71 | * Show edit user form
72 | *
73 | * @param User $user
74 | * @return Response
75 | */
76 | public function edit(User $user) {
77 | return Inertia::render('users/createOrEdit', [
78 | 'edit_user' => [
79 | 'id' => $user->id,
80 | 'email' => $user->email,
81 | 'name' => $user->name
82 | ]
83 | ]);
84 | }
85 |
86 | public function update(CreateOrEditUser $request, User $user) {
87 | $user->update($request->input());
88 |
89 | return redirect()
90 | ->route(
91 | 'admin.users.edit',
92 | [
93 | "user" => $user->id
94 | ]
95 | )
96 | ->with(['success' => 'User updated successfully']);
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/resources/js/components/flags/us.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export const FlagUS: React.FC> = (props) => {
4 | return (
5 |
52 | );
53 | };
54 |
--------------------------------------------------------------------------------
/resources/js/pages/auth/forgot-password.tsx:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2 | // @ts-ignore
3 | import { useForm } from '@inertiajs/inertia-react';
4 | import React from 'react';
5 | import { Helmet } from 'react-helmet';
6 | import { route } from 'ziggy-js';
7 | import Input from '../../components/form/input';
8 |
9 | const ForgotPassword: React.FC = () => {
10 | const [successMessage, showSuccessMessage] = React.useState(false);
11 | const { data, setData, post, processing, errors } = useForm({
12 | email: '',
13 | });
14 |
15 | const submit = (e: React.FormEvent): void => {
16 | e.preventDefault();
17 | post(route('password.email'), {
18 | onSuccess: () => {
19 | showSuccessMessage(true);
20 | },
21 | });
22 | };
23 |
24 | return (
25 |
72 | );
73 | };
74 |
75 | export default ForgotPassword;
76 |
--------------------------------------------------------------------------------
/app/Models/Election.php:
--------------------------------------------------------------------------------
1 | 'array',
49 | 'published' => 'boolean',
50 | 'playable' => 'boolean',
51 | ];
52 |
53 | /**
54 | * Get the options for generating the slug.
55 | */
56 | public function getSlugOptions(): SlugOptions
57 | {
58 | return SlugOptions::create()
59 | ->generateSlugsFrom('name')
60 | ->saveSlugsTo('slug');
61 | }
62 |
63 | protected $appends = [
64 | 'parties_participating',
65 | 'parties_not_participating'
66 | ];
67 |
68 | /**
69 | * Get the country
70 | */
71 | public function country(): BelongsTo
72 | {
73 | return $this->belongsTo(Country::class);
74 | }
75 |
76 | /**
77 | * Get the uploaded file
78 | */
79 | public function card(): BelongsTo
80 | {
81 | return $this->belongsTo(Upload::class, 'card_upload_id', 'id');
82 | }
83 |
84 | /*
85 | * The elections questions
86 | */
87 | public function questions(): HasMany
88 | {
89 | return $this->hasMany(Question::class);
90 | }
91 |
92 | public function parties(): BelongsToMany
93 | {
94 | return $this->belongsToMany(Party::class)
95 | ->using(ElectionParty::class)
96 | ->withPivot('playable', 'published', 'program_upload_id', 'program_link', 'id')
97 | ->withTimestamps();
98 | }
99 |
100 | public function getPartiesParticipatingAttribute() {
101 | return $this->parties()->wherePivot('playable', true)->count();
102 | }
103 |
104 | public function getPartiesNotParticipatingAttribute() {
105 | return $this->parties()->wherePivot('playable', false)->count();
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/config/queue.php:
--------------------------------------------------------------------------------
1 | env('QUEUE_CONNECTION', 'sync'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Queue Connections
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure the connection information for each server that
24 | | is used by your application. A default configuration has been added
25 | | for each back-end shipped with Laravel. You are free to add more.
26 | |
27 | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'sync' => [
34 | 'driver' => 'sync',
35 | ],
36 |
37 | 'database' => [
38 | 'driver' => 'database',
39 | 'table' => 'jobs',
40 | 'queue' => 'default',
41 | 'retry_after' => 90,
42 | ],
43 |
44 | 'beanstalkd' => [
45 | 'driver' => 'beanstalkd',
46 | 'host' => 'localhost',
47 | 'queue' => 'default',
48 | 'retry_after' => 90,
49 | 'block_for' => 0,
50 | ],
51 |
52 | 'sqs' => [
53 | 'driver' => 'sqs',
54 | 'key' => env('AWS_ACCESS_KEY_ID'),
55 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
56 | 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
57 | 'queue' => env('SQS_QUEUE', 'your-queue-name'),
58 | 'suffix' => env('SQS_SUFFIX'),
59 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
60 | ],
61 |
62 | 'redis' => [
63 | 'driver' => 'redis',
64 | 'connection' => 'default',
65 | 'queue' => env('REDIS_QUEUE', 'default'),
66 | 'retry_after' => 90,
67 | 'block_for' => null,
68 | ],
69 |
70 | ],
71 |
72 | /*
73 | |--------------------------------------------------------------------------
74 | | Failed Queue Jobs
75 | |--------------------------------------------------------------------------
76 | |
77 | | These options configure the behavior of failed queue job logging so you
78 | | can control which database and table are used to store the jobs that
79 | | have failed. You may change them to any database / table you wish.
80 | |
81 | */
82 |
83 | 'failed' => [
84 | 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
85 | 'database' => env('DB_CONNECTION', 'mysql'),
86 | 'table' => 'failed_jobs',
87 | ],
88 |
89 | ];
90 |
--------------------------------------------------------------------------------
/resources/js/pages/statistic/election.tsx:
--------------------------------------------------------------------------------
1 | import { Page as PageType } from '@inertiajs/inertia';
2 | import { usePage } from '@inertiajs/inertia-react';
3 | import React from 'react';
4 | import { Helmet } from 'react-helmet';
5 | import { Layout } from '../../components/layout';
6 | import { Page } from '../../components/page';
7 |
8 | interface Props {
9 | election: Election;
10 | swipes: number;
11 | initiations: number;
12 | results: number;
13 | }
14 |
15 | const StatisticElection: InertiaPage = () => {
16 | const { props } = usePage>();
17 |
18 | return (
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
Swipes
27 |
28 | {Intl.NumberFormat('de').format(props.swipes)}
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
Initiations
38 |
39 | {Intl.NumberFormat('de').format(
40 | props.initiations
41 | )}
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
Results
51 |
52 |
53 | {Intl.NumberFormat('de').format(
54 | props.results
55 | )}
56 |
57 |
58 | {(
59 | (props.results * 100) /
60 | props.initiations
61 | ).toFixed(2)}
62 | %
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 | );
71 | };
72 |
73 | StatisticElection.layout = (page) => {page};
74 |
75 | export default StatisticElection;
76 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Api/V1/PartyController.php:
--------------------------------------------------------------------------------
1 | header('API-Preview-Key', 'default') === env('API_PREVIEW_KEY');
28 |
29 | if (!$request->input('slug') && !$request->input('id')) {
30 | throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException('No election slug or id was provided.');
31 | }
32 |
33 | $currentLocale = App::getLocale();
34 | $value = $request->input('id') ?? $request->input('slug');
35 |
36 | $cacheKey = $currentLocale . '_parties_' . $value;
37 |
38 | if (!Cache::has($cacheKey) || $isPreview) {
39 | if ($request->input('id')) {
40 | $election = Election::where('id', $request->input('id'));
41 | } else {
42 | $election = Election::where(function($query) use($request, $currentLocale) {
43 | $query->where('slug->' . $currentLocale, $request->input('slug'))->orWhere('slug->en', $request->input('slug'));
44 | });
45 | }
46 |
47 | if ($isPreview) {
48 | $election = $election->with('card')->firstOrFail();
49 |
50 | $parties = $election->parties()->where('playable', true)->with('logo')->orderBy('name')->get();
51 | } else {
52 | $election = $election->where('published', true)->with('card')->firstOrFail();
53 |
54 | $parties = $election->parties()->where('playable', true)->where('published', true)->with('logo')->orderBy('name')->get();
55 | }
56 |
57 |
58 | $list = [];
59 |
60 | foreach($parties as $party) {
61 | $list[] = array_merge(
62 | $party->toArray(),
63 | [
64 | 'pivot' => array_merge(
65 | $party->pivot->toArray(),
66 | [
67 | 'answers' => $party->pivot->answers,
68 | 'program' => $party->pivot->program
69 | ]
70 | )
71 | ]
72 | );
73 | }
74 |
75 | if (!$isPreview) {
76 | Cache::put($cacheKey, $list, now()->addMinutes(120));
77 | }
78 | }
79 |
80 | if ($isPreview) {
81 | return $list;
82 | }
83 |
84 | return Cache::get($cacheKey);
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/resources/js/components/form/datepicker.tsx:
--------------------------------------------------------------------------------
1 | import cn from 'classnames';
2 | import { format } from 'date-fns';
3 | import React from 'react';
4 | import DP from 'react-datepicker';
5 | import createDateFromMysql from '../../util/create-date-from-mysql';
6 |
7 | interface Props {
8 | label?: string;
9 | error: boolean;
10 | helperText?: string | React.ReactNode;
11 | showTimeSelect?: boolean;
12 | value: string;
13 | required?: boolean;
14 | disabled?: boolean;
15 | id?: string;
16 | onChange: (date: string) => void;
17 | }
18 |
19 | function convertUTCToLocalDate(date: string | Date): Date {
20 | const newDate = new Date(date);
21 | return new Date(
22 | newDate.getUTCFullYear(),
23 | newDate.getUTCMonth(),
24 | newDate.getUTCDate(),
25 | newDate.getUTCHours(),
26 | newDate.getUTCMinutes(),
27 | newDate.getUTCSeconds()
28 | );
29 | }
30 |
31 | function convertLocalToUTCDate(date: string | Date): Date {
32 | const newDate = new Date(date);
33 | return new Date(
34 | Date.UTC(
35 | newDate.getFullYear(),
36 | newDate.getMonth(),
37 | newDate.getDate(),
38 | newDate.getHours(),
39 | newDate.getMinutes(),
40 | newDate.getSeconds()
41 | )
42 | );
43 | }
44 |
45 | const Datepicker: React.FC = ({
46 | label,
47 | error,
48 | helperText,
49 | required = false,
50 | disabled = false,
51 | id,
52 | onChange,
53 | value,
54 | showTimeSelect = false,
55 | }) => {
56 | const selected = React.useMemo(() => {
57 | if (value === '' || !value) return null;
58 | return convertUTCToLocalDate(createDateFromMysql(value) as Date);
59 | }, [value]);
60 |
61 | return (
62 |
63 | {label &&
}
64 |
65 | {
72 | onChange(
73 | format(
74 | convertLocalToUTCDate(date),
75 | 'yyyy-MM-dd HH:mm:ss'
76 | )
77 | );
78 | }}
79 | showTimeSelect={showTimeSelect}
80 | dateFormat={
81 | showTimeSelect ? 'MMMM d, yyyy HH:mm' : undefined
82 | }
83 | />
84 |
85 | {helperText && (
86 |
91 | {helperText}
92 |
93 | )}
94 |
95 |
96 | );
97 | };
98 |
99 | export default Datepicker;
100 |
--------------------------------------------------------------------------------
/config/logging.php:
--------------------------------------------------------------------------------
1 | env('LOG_CHANNEL', 'stack'),
21 |
22 | /*
23 | |--------------------------------------------------------------------------
24 | | Log Channels
25 | |--------------------------------------------------------------------------
26 | |
27 | | Here you may configure the log channels for your application. Out of
28 | | the box, Laravel uses the Monolog PHP logging library. This gives
29 | | you a variety of powerful log handlers / formatters to utilize.
30 | |
31 | | Available Drivers: "single", "daily", "slack", "syslog",
32 | | "errorlog", "monolog",
33 | | "custom", "stack"
34 | |
35 | */
36 |
37 | 'channels' => [
38 | 'stack' => [
39 | 'driver' => 'stack',
40 | 'channels' => ['single'],
41 | 'ignore_exceptions' => false,
42 | ],
43 |
44 | 'single' => [
45 | 'driver' => 'single',
46 | 'path' => storage_path('logs/laravel.log'),
47 | 'level' => env('LOG_LEVEL', 'debug'),
48 | ],
49 |
50 | 'daily' => [
51 | 'driver' => 'daily',
52 | 'path' => storage_path('logs/laravel.log'),
53 | 'level' => env('LOG_LEVEL', 'debug'),
54 | 'days' => 14,
55 | ],
56 |
57 | 'slack' => [
58 | 'driver' => 'slack',
59 | 'url' => env('LOG_SLACK_WEBHOOK_URL'),
60 | 'username' => 'Laravel Log',
61 | 'emoji' => ':boom:',
62 | 'level' => env('LOG_LEVEL', 'critical'),
63 | ],
64 |
65 | 'papertrail' => [
66 | 'driver' => 'monolog',
67 | 'level' => env('LOG_LEVEL', 'debug'),
68 | 'handler' => SyslogUdpHandler::class,
69 | 'handler_with' => [
70 | 'host' => env('PAPERTRAIL_URL'),
71 | 'port' => env('PAPERTRAIL_PORT'),
72 | ],
73 | ],
74 |
75 | 'stderr' => [
76 | 'driver' => 'monolog',
77 | 'handler' => StreamHandler::class,
78 | 'formatter' => env('LOG_STDERR_FORMATTER'),
79 | 'with' => [
80 | 'stream' => 'php://stderr',
81 | ],
82 | ],
83 |
84 | 'syslog' => [
85 | 'driver' => 'syslog',
86 | 'level' => env('LOG_LEVEL', 'debug'),
87 | ],
88 |
89 | 'errorlog' => [
90 | 'driver' => 'errorlog',
91 | 'level' => env('LOG_LEVEL', 'debug'),
92 | ],
93 |
94 | 'null' => [
95 | 'driver' => 'monolog',
96 | 'handler' => NullHandler::class,
97 | ],
98 |
99 | 'emergency' => [
100 | 'path' => storage_path('logs/laravel.log'),
101 | ],
102 | ],
103 |
104 | ];
105 |
--------------------------------------------------------------------------------
/resources/js/pages/auth/login.tsx:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2 | // @ts-ignore
3 | import { InertiaLink, useForm } from '@inertiajs/inertia-react';
4 | import React from 'react';
5 | import { Helmet } from 'react-helmet';
6 | import { route } from 'ziggy-js';
7 | import Input from '../../components/form/input';
8 |
9 | const Login: React.FC = () => {
10 | const { data, setData, post, processing, errors } = useForm({
11 | email: '',
12 | password: '',
13 | });
14 |
15 | const submit = (e: React.FormEvent): void => {
16 | e.preventDefault();
17 | post(route('login'));
18 | };
19 |
20 | return (
21 |
22 |
23 |
24 |
25 |
VoteSwiper
26 |
27 |
28 |
78 |
79 |
80 |
81 | Forgot password?
82 |
83 |
84 |
85 |
86 | );
87 | };
88 |
89 | export default Login;
90 |
--------------------------------------------------------------------------------
/config/cache.php:
--------------------------------------------------------------------------------
1 | env('CACHE_DRIVER', 'file'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Cache Stores
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the cache "stores" for your application as
26 | | well as their drivers. You may even define multiple stores for the
27 | | same cache driver to group types of items stored in your caches.
28 | |
29 | | Supported drivers: "apc", "array", "database", "file",
30 | | "memcached", "redis", "dynamodb", "null"
31 | |
32 | */
33 |
34 | 'stores' => [
35 |
36 | 'apc' => [
37 | 'driver' => 'apc',
38 | ],
39 |
40 | 'array' => [
41 | 'driver' => 'array',
42 | 'serialize' => false,
43 | ],
44 |
45 | 'database' => [
46 | 'driver' => 'database',
47 | 'table' => 'cache',
48 | 'connection' => null,
49 | 'lock_connection' => null,
50 | ],
51 |
52 | 'file' => [
53 | 'driver' => 'file',
54 | 'path' => storage_path('framework/cache/data'),
55 | ],
56 |
57 | 'memcached' => [
58 | 'driver' => 'memcached',
59 | 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
60 | 'sasl' => [
61 | env('MEMCACHED_USERNAME'),
62 | env('MEMCACHED_PASSWORD'),
63 | ],
64 | 'options' => [
65 | // Memcached::OPT_CONNECT_TIMEOUT => 2000,
66 | ],
67 | 'servers' => [
68 | [
69 | 'host' => env('MEMCACHED_HOST', '127.0.0.1'),
70 | 'port' => env('MEMCACHED_PORT', 11211),
71 | 'weight' => 100,
72 | ],
73 | ],
74 | ],
75 |
76 | 'redis' => [
77 | 'driver' => 'redis',
78 | 'connection' => 'cache',
79 | 'lock_connection' => 'default',
80 | ],
81 |
82 | 'dynamodb' => [
83 | 'driver' => 'dynamodb',
84 | 'key' => env('AWS_ACCESS_KEY_ID'),
85 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
86 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
87 | 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
88 | 'endpoint' => env('DYNAMODB_ENDPOINT'),
89 | ],
90 |
91 | ],
92 |
93 | /*
94 | |--------------------------------------------------------------------------
95 | | Cache Key Prefix
96 | |--------------------------------------------------------------------------
97 | |
98 | | When utilizing a RAM based store such as APC or Memcached, there might
99 | | be other applications utilizing the same cache. So, we'll specify a
100 | | value to get prefixed to all our keys so we can avoid collisions.
101 | |
102 | */
103 |
104 | 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
105 |
106 | ];
107 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Admin/PartyController.php:
--------------------------------------------------------------------------------
1 | with('country', 'logo');
28 |
29 | if ($request->get('country')) {
30 | $parties->where('country_id', $request->get('country'));
31 | }
32 |
33 | return Inertia::render('parties', [
34 | 'parties' => $parties->get()
35 | ]);
36 | }
37 |
38 | /**
39 | * Show form for creating party
40 | *
41 | * @return RedirectResponse|Response
42 | * @throws BindingResolutionException
43 | * @throws RouteNotFoundException
44 | */
45 | public function create()
46 | {
47 | $countries = Country::orderBy('name')->get(['id', 'name']);
48 |
49 | return Inertia::render('parties/createOrEdit', [
50 | 'countries' => $countries
51 | ]);
52 | }
53 |
54 | /**
55 | * Store the new party
56 | *
57 | * @param CreateOrEditParty $request
58 | * @return RedirectResponse
59 | * @throws BindingResolutionException
60 | * @throws RouteNotFoundException
61 | */
62 | public function store(CreateOrEditParty $request) {
63 | $data = $request->input();
64 |
65 | $image = Upload::add($request->file('logo'), 'parties');
66 | $data['logo_upload_id'] = $image->id;
67 |
68 | Party::create($data);
69 |
70 | return redirect()->route('admin.parties')->with(['success' => 'The parties was created successfully.']);
71 | }
72 |
73 | /**
74 | * Show edit party form
75 | *
76 | * @param Party $party
77 | * @return Response
78 | */
79 | public function edit(Party $party) {
80 | $countries = Country::orderBy('name')->get(['id', 'name']);
81 | return Inertia::render('parties/createOrEdit', [
82 | 'party' => $party->with('logo')->find($party->id),
83 | 'countries' => $countries
84 | ]);
85 | }
86 |
87 | /**
88 | * Store the updated party
89 | *
90 | * @param CreateOrEditParty $request
91 | * @param Party $party
92 | * @return RedirectResponse
93 | * @throws MassAssignmentException
94 | * @throws BindingResolutionException
95 | * @throws RouteNotFoundException
96 | */
97 | public function update(CreateOrEditParty $request, Party $party) {
98 | $data = $request->input();
99 |
100 | if ($request->file('logo')) {
101 | $image = Upload::add($request->file('logo'), 'parties');
102 | $data['logo_upload_id'] = $image->id;
103 | }
104 |
105 | $party->update($data);
106 |
107 | return redirect()
108 | ->route(
109 | 'admin.parties.edit',
110 | [
111 | "party" => $party->id
112 | ]
113 | )
114 | ->with(['success' => 'Party updated successfully']);
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Admin/CountryController.php:
--------------------------------------------------------------------------------
1 | withCount('parties')->get();
26 |
27 | return Inertia::render('countries', [
28 | 'countries' => $countries
29 | ]);
30 | }
31 |
32 | /**
33 | * Show form for creating country
34 | *
35 | * @return RedirectResponse|Response
36 | * @throws BindingResolutionException
37 | * @throws RouteNotFoundException
38 | */
39 | public function create()
40 | {
41 | if (App::currentLocale() !== 'en') {
42 | return redirect()->route('admin.locale', [
43 | 'key' => 'en',
44 | 'redirect' => route('admin.countries.create')
45 | ]);
46 | }
47 |
48 | return Inertia::render('countries/createOrEdit');
49 | }
50 |
51 | /**
52 | * Store the new country
53 | *
54 | * @param CreateOrEditCountry $request
55 | * @return RedirectResponse
56 | * @throws BindingResolutionException
57 | * @throws RouteNotFoundException
58 | */
59 | public function store(CreateOrEditCountry $request) {
60 | $country = Country::create($request->input());
61 |
62 | return redirect()->route('admin.countries')->with(['success' => 'The country was created successfully.']);
63 | }
64 |
65 | /**
66 | * Show edit user form
67 | *
68 | * @param Country $country
69 | * @return Response
70 | */
71 | public function edit(Country $country) {
72 | return Inertia::render('countries/createOrEdit', [
73 | 'country' => array_merge($country->toArray(), [
74 | 'name' => $country->getTranslation('name', App::currentLocale(), false),
75 | 'slug' => $country->getTranslation('slug', App::currentLocale(), false),
76 | ]),
77 | ]);
78 | }
79 |
80 | /**
81 | * Store the updated country
82 | *
83 | * @param CreateOrEditCountry $request
84 | * @param Country $country
85 | * @return RedirectResponse
86 | * @throws MassAssignmentException
87 | * @throws BindingResolutionException
88 | * @throws RouteNotFoundException
89 | */
90 | public function update(CreateOrEditCountry $request, Country $country) {
91 | $country->update($request->input());
92 |
93 | return redirect()
94 | ->route(
95 | 'admin.countries.edit',
96 | [
97 | "country" => $country->id
98 | ]
99 | )
100 | ->with(['success' => 'Country updated successfully']);
101 | }
102 |
103 | /**
104 | * Display details for a country
105 | *
106 | * @param Country $country
107 | * @return Response
108 | */
109 | public function show(Country $country) {
110 | return Inertia::render('countries/show', [
111 | 'country' => array_merge($country->toArray(), $country->getTranslations())
112 | ]);
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/config/mail.php:
--------------------------------------------------------------------------------
1 | env('MAIL_MAILER', 'smtp'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Mailer Configurations
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure all of the mailers used by your application plus
24 | | their respective settings. Several examples have been configured for
25 | | you and you are free to add your own as your application requires.
26 | |
27 | | Laravel supports a variety of mail "transport" drivers to be used while
28 | | sending an e-mail. You will specify which one you are using for your
29 | | mailers below. You are free to add additional mailers as required.
30 | |
31 | | Supported: "smtp", "sendmail", "mailgun", "ses",
32 | | "postmark", "log", "array"
33 | |
34 | */
35 |
36 | 'mailers' => [
37 | 'smtp' => [
38 | 'transport' => 'smtp',
39 | 'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
40 | 'port' => env('MAIL_PORT', 587),
41 | 'encryption' => env('MAIL_ENCRYPTION', 'tls'),
42 | 'username' => env('MAIL_USERNAME'),
43 | 'password' => env('MAIL_PASSWORD'),
44 | 'timeout' => null,
45 | 'auth_mode' => null,
46 | ],
47 |
48 | 'ses' => [
49 | 'transport' => 'ses',
50 | ],
51 |
52 | 'mailgun' => [
53 | 'transport' => 'mailgun',
54 | ],
55 |
56 | 'postmark' => [
57 | 'transport' => 'postmark',
58 | ],
59 |
60 | 'sendmail' => [
61 | 'transport' => 'sendmail',
62 | 'path' => '/usr/sbin/sendmail -bs',
63 | ],
64 |
65 | 'log' => [
66 | 'transport' => 'log',
67 | 'channel' => env('MAIL_LOG_CHANNEL'),
68 | ],
69 |
70 | 'array' => [
71 | 'transport' => 'array',
72 | ],
73 | ],
74 |
75 | /*
76 | |--------------------------------------------------------------------------
77 | | Global "From" Address
78 | |--------------------------------------------------------------------------
79 | |
80 | | You may wish for all e-mails sent by your application to be sent from
81 | | the same address. Here, you may specify a name and address that is
82 | | used globally for all e-mails that are sent by your application.
83 | |
84 | */
85 |
86 | 'from' => [
87 | 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
88 | 'name' => env('MAIL_FROM_NAME', 'Example'),
89 | ],
90 |
91 | /*
92 | |--------------------------------------------------------------------------
93 | | Markdown Mail Settings
94 | |--------------------------------------------------------------------------
95 | |
96 | | If you are using Markdown based email rendering, you may configure your
97 | | theme and component paths here, allowing you to customize the design
98 | | of the emails. Or, you may simply stick with the Laravel defaults!
99 | |
100 | */
101 |
102 | 'markdown' => [
103 | 'theme' => 'default',
104 |
105 | 'paths' => [
106 | resource_path('views/vendor/mail'),
107 | ],
108 | ],
109 |
110 | ];
111 |
--------------------------------------------------------------------------------
/app/Models/Upload.php:
--------------------------------------------------------------------------------
1 | 'number',
60 | 'height' => 'number',
61 | ];
62 |
63 | /**
64 | * Upload a file and save it in the database
65 | *
66 | * @param UploadedFile $file The uploaded file
67 | * @param string $pathPrefix Prefix for path
68 | * @return Upload
69 | * @throws Exception
70 | * @throws LogicException
71 | * @throws InvalidArgumentException
72 | * @throws ExceptionLogicException
73 | * @throws BindingResolutionException
74 | * @throws Throwable
75 | */
76 | public static function add(UploadedFile $file, string $pathPrefix = '', int | null $assetId = null) {
77 | if (!$assetId) {
78 | $preseveLocal = App::getLocale();
79 |
80 | App::setLocale('en');
81 | }
82 |
83 | $uploadedFileName = $file->getClientOriginalName();
84 |
85 | $path = (!empty($pathPrefix) ? $pathPrefix . '/' : '') . uniqid();
86 |
87 | $filename = pathinfo($uploadedFileName, PATHINFO_FILENAME);
88 | $extension = pathinfo($uploadedFileName, PATHINFO_EXTENSION);
89 |
90 | if ($assetId) {
91 | $upload = self::find($assetId);
92 | } else {
93 | $upload = new self;
94 | }
95 |
96 | $safeFilename = Str::slug($filename) . '-' . Str::random(5) . '.' . $extension;
97 | $storedFilename = $path . '/' . $safeFilename;
98 |
99 | $upload->filename = $storedFilename;
100 | $upload->filetype = $file->getMimeType();
101 | $upload->filesize = $file->getSize();
102 |
103 | if(substr($file->getMimeType(), 0, 5) == 'image' && $extension !== 'svg') {
104 | $dimensions = getimagesize($file);
105 | $upload->width = $dimensions[0];
106 | $upload->height = $dimensions[1];
107 | } else {
108 | $upload->width = 0;
109 | $upload->height = 0;
110 | }
111 |
112 | $file->storePubliclyAs($path, $safeFilename);
113 |
114 | $upload->saveOrFail();
115 |
116 | if (!$assetId) {
117 | App::setLocale($preseveLocal);
118 | }
119 |
120 | return $upload;
121 | }
122 |
123 | /**
124 | * Get the full URL for this asset
125 | *
126 | * @return string
127 | */
128 | public function getPublicLinkAttribute()
129 | {
130 | return Storage::url($this->filename);
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Api/V1/CountryController.php:
--------------------------------------------------------------------------------
1 | orderBy('name->' . App::getLocale(), 'ASC')->get();
29 | Cache::put($cacheKey, $countries, now()->addMinutes(120));
30 | }
31 |
32 | return Cache::get($cacheKey);
33 | }
34 |
35 | /**
36 | * Get country
37 | *
38 | * Fetch a single country
39 | *
40 | * @Get("/countryBySlug)
41 | * @Versions({"v1"})
42 | * @Request({"slug": "germany"}, headers={"Content-Language": "en"})
43 | */
44 | public function countryBySlug(Request $request)
45 | {
46 | if (!isset($request->input()["slug"])) {
47 | throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException('No slug was provided.');
48 | }
49 |
50 | $slug = $request->input()["slug"];
51 | $currentLocale = App::getLocale();
52 |
53 | $cacheKey = $currentLocale . '_countryBySlug_' . $slug;
54 |
55 | if (!Cache::has($cacheKey)) {
56 | $country = Country::where(function($query) use($slug, $currentLocale) {
57 | $query->where('slug->' . $currentLocale, $slug)->orWhere('slug->en', $slug);
58 | })->where('published', true)->firstOrFail();
59 |
60 | Cache::put($cacheKey, $country, now()->addMinutes(120));
61 | }
62 |
63 | return Cache::get($cacheKey);
64 | }
65 |
66 | /**
67 | * Country Alternative Links
68 | *
69 | * Fetches "alternate" links used in hreflang meta tags based on the current slug
70 | *
71 | * @Get("/alternateCountrySlugs")
72 | * @Versions({"v1"})
73 | * @Request({"slug": "germany"}, headers={"Content-Language": "en"})
74 | * @Response(200, body={"en": "germany", "de": "deutschland", "fr": "allemagne"})
75 | */
76 | public function alternateCountrySlugs(Request $request)
77 | {
78 | if (!isset($request->input()["slug"])) {
79 | throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException('No slug was provided.');
80 | }
81 |
82 | $slug = $request->input()["slug"];
83 | $currentLocale = App::getLocale();
84 |
85 | $cacheKey = $currentLocale . '_alternateCountrySlugs_' . $slug;
86 |
87 | if (!Cache::has($cacheKey)) {
88 | $list = [];
89 |
90 | $country = Country::where(function($query) use($slug, $currentLocale) {
91 | $query->where('slug->' . $currentLocale, $slug)->orWhere('slug->en', $slug);
92 | })->where('published', true)->firstOrFail();
93 | $translations = $country->getTranslations();
94 |
95 | foreach(config('app.locales') as $locale) {
96 | $list[$locale] = $translations["slug"][$locale] ?? $translations["slug"]["en"];
97 | }
98 |
99 | Cache::put($cacheKey, $list, now()->addMinutes(120));
100 | }
101 |
102 | return Cache::get($cacheKey);
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/resources/js/pages/users/index.tsx:
--------------------------------------------------------------------------------
1 | import { Page as PageType } from '@inertiajs/inertia';
2 | import { InertiaLink, usePage } from '@inertiajs/inertia-react';
3 | import { IconPlus } from '@tabler/icons-react';
4 | import React from 'react';
5 | import { Helmet } from 'react-helmet';
6 | import { route } from 'ziggy-js';
7 | import { Layout } from '../../components/layout';
8 | import { Page } from '../../components/page';
9 |
10 | interface Props {
11 | users: Array<{
12 | id: number;
13 | name: string;
14 | email: string;
15 | }>;
16 | }
17 |
18 | const Users: InertiaPage = () => {
19 | const { props } = usePage>();
20 |
21 | const { users } = props;
22 |
23 | return (
24 |
28 |
32 |
33 | Add new user
34 |
35 |
36 | }
37 | >
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | | ID |
48 | Name |
49 | E-Mail |
50 | Actions |
51 |
52 |
53 |
54 | {users.map((user) => {
55 | return (
56 |
57 | | {user.id} |
58 | {user.name} |
59 | {user.email} |
60 |
61 |
62 |
71 | Edit
72 |
73 |
74 | |
75 |
76 | );
77 | })}
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 | );
86 | };
87 |
88 | Users.layout = (page) => {page};
89 |
90 | export default Users;
91 |
--------------------------------------------------------------------------------