+ {/* ) : (
- )}
+ )} */}
diff --git a/browser-extension/plugin/src/ui-components/pages/Debug.jsx b/browser-extension/plugin/src/ui-components/pages/Debug.jsx
index feee16d9..77ade592 100644
--- a/browser-extension/plugin/src/ui-components/pages/Debug.jsx
+++ b/browser-extension/plugin/src/ui-components/pages/Debug.jsx
@@ -1,5 +1,14 @@
import { useEffect, useContext, useState } from 'react';
-import { Box, Text, Button, CheckBox } from 'grommet';
+import {
+ Box,
+ Text,
+ Button,
+ CheckBox,
+ Form,
+ FormField,
+ TextInput,
+ Heading
+} from 'grommet';
import { UserContext } from '../atoms/AppContext';
import repository from '../../repository';
import config from '../../config';
@@ -8,10 +17,11 @@ import Api from './Api';
const { getUserData, getPreferenceData, setUserData, setPreferenceData } =
repository;
const { resetAccount } = Api;
+import { Hide, View } from 'grommet-icons';
export function Debug() {
const { user, setUser } = useContext(UserContext);
- const [isResetChecked, setIsResetChecked] = useState(false);
+
const [localStorageData, setLocalStorageData] = useState(undefined);
const { t, i18n } = useTranslation();
@@ -19,97 +29,206 @@ export function Debug() {
async function localStorage() {
const userData = await getUserData();
const preferenceData = await getPreferenceData();
- if(!ignore) {
- setLocalStorageData({ user: userData, preference: preferenceData });
+ if (!ignore) {
+ setLocalStorageData({
+ user: userData,
+ preference: preferenceData
+ });
}
-
}
let ignore = false;
localStorage();
return () => {
ignore = true;
- }
+ };
}, []);
- async function clickReset() {
- try {
- await resetAccount(user.accessToken);
- await setUserData({});
- await setPreferenceData({});
- setUser(undefined);
- } catch (err) {
- console.log(err);
- // alert('Error Resetting User', err);
- }
- }
+ return {user ? Logged in. Settings : };
+}
+
+const LoginForm = () => {
+ const [reveal, setReveal] = useState(false);
+ const [formValues, setFormValues] = useState({ email: '', password: '' });
+
+ const handleSubmit = ({ value }) => {
+ console.log('Form Submitted:', value);
+ };
return (
-
- {/* {config ? (
-
- Config
- {JSON.stringify(config, null, 2)}
-
- ) : (
-
- {t('message_error_config_data')}
-
- )} */}
- {user ? (
-
-
- {/* Environment :
- {config.ENVIRONMENT} */}
- User ID :
- {user.id}
- {/* Access Token :
- {user.accessToken} */}
-
+
+
+
+ Login
+
+
+
);
-}
+};
+
+// import { useEffect, useContext, useState } from 'react';
+// import { Box, Text, Button, CheckBox } from 'grommet';
+// import { UserContext } from '../atoms/AppContext';
+// import repository from '../../repository';
+// import config from '../../config';
+// import { useTranslation } from 'react-i18next';
+// import Api from './Api';
+// const { getUserData, getPreferenceData, setUserData, setPreferenceData } =
+// repository;
+// const { resetAccount } = Api;
+
+// export function Debug() {
+// const { user, setUser } = useContext(UserContext);
+// const [isResetChecked, setIsResetChecked] = useState(false);
+// const [localStorageData, setLocalStorageData] = useState(undefined);
+// const { t, i18n } = useTranslation();
+
+// useEffect(() => {
+// async function localStorage() {
+// const userData = await getUserData();
+// const preferenceData = await getPreferenceData();
+// if(!ignore) {
+// setLocalStorageData({ user: userData, preference: preferenceData });
+// }
+
+// }
+// let ignore = false;
+// localStorage();
+// return () => {
+// ignore = true;
+// }
+// }, []);
+
+// async function clickReset() {
+// try {
+// await resetAccount(user.accessToken);
+// await setUserData({});
+// await setPreferenceData({});
+// setUser(undefined);
+// } catch (err) {
+// console.log(err);
+// // alert('Error Resetting User', err);
+// }
+// }
+
+// return (
+//
+// {/* {config ? (
+//
+// Config
+// {JSON.stringify(config, null, 2)}
+//
+// ) : (
+//
+// {t('message_error_config_data')}
+//
+// )} */}
+// {user ? (
+//
+//
+// {/* Environment :
+// {config.ENVIRONMENT} */}
+// User ID :
+// {user.id}
+// {/* Access Token :
+// {user.accessToken} */}
+//
+
+// {/* {localStorageData ? (
+//
+// Local Storage
+//
+// {JSON.stringify(localStorageData, null, 2)}
+//
+//
+// ) : (
+//
+// {t('message_error_local_storage')}
+//
+// )} */}
+
+//
+//
+// {t('reset_account')}
+//
+//
+//
+//
+// setIsResetChecked(e.target.checked)
+// }
+// />
+//
+//
+//
+//
+// ) : (
+// {t('message_no_user')}
+// )}
+//
+// );
+// }
diff --git a/browser-extension/plugin/src/ui-components/pages/Preferences.jsx b/browser-extension/plugin/src/ui-components/pages/Preferences.jsx
index 6c1d0810..1c4f729a 100644
--- a/browser-extension/plugin/src/ui-components/pages/Preferences.jsx
+++ b/browser-extension/plugin/src/ui-components/pages/Preferences.jsx
@@ -8,7 +8,8 @@ import {
Text,
Button,
Select,
- CheckBox
+ CheckBox,
+ RadioButtonGroup
} from 'grommet';
// import { HelpCircle } from 'react-feather';
import Api from '../pages/Api';
@@ -19,28 +20,54 @@ import { langNameMap } from '../atoms/language';
const { savePreference } = Api;
import { UserContext, NotificationContext } from '../atoms/AppContext';
import { userBrowserTabs } from '../../browser-compat';
+import { Link, Outlet, useNavigate } from 'react-router-dom';
+import { FormClose, FormPreviousLink, LinkPrevious } from 'grommet-icons';
const { setPreferenceData, getPreferenceData } = repository;
const defaultValue = {};
export function Preferences() {
+ return ;
+}
+
+export function PreferencesHome() {
const [localPreferences, setLocalPreferences] = useState(defaultValue);
const { user } = useContext(UserContext);
const { showNotification } = useContext(NotificationContext);
const [enable, setEnable] = useState(true);
- const [enableML, setEnableMLOption] = useState(false);
const [enableSlurReplacement, setEnableSlurReplacement] = useState(true);
const [enableSlurMetadata, setEnableSlurMetadata] = useState(false);
- const [storeLocally, setStoreLocally] = useState(true);
const [language, setLanguage] = useState('English');
const { t, i18n } = useTranslation();
+ const radioOptions = [
+ {
+ value: 'replace',
+ id: 'radio-replace',
+ label: 'Enable Slur Replacement'
+ },
+ {
+ value: 'metadata',
+ id: 'radio-metadata',
+ label: 'Enable Slur Metadata'
+ },
+ {
+ value: 'off',
+ id: 'radio-off',
+ label: 'Turn off'
+ }
+ ];
+ const [selectedOption, setSelectedOption] = useState(undefined);
// GET PREFERENCE FOR THIS USER FROM LS
+
useEffect(() => {
async function getPrefsLocalStorage() {
try {
const preference = await getPreferenceData();
- console.log("preference " , preference)
+ console.log('preference ', preference);
+
+ const { enableSlurMetadata, enableSlurReplacement, language } =
+ preference;
if (!ignore) {
// console.log({ preference });
setLocalPreferences(preference);
@@ -48,31 +75,25 @@ export function Preferences() {
preference != undefined &&
Object.keys(preference).length != 0
) {
- const {
- enable,
- enableML,
- storeLocally,
- language,
- enableSlurReplacement,
- enableSlurMetadata
- } = preference;
- if (enable != undefined) {
- setEnable(enable);
- }
- if (enableML != undefined) {
- setEnableMLOption(enableML);
- }
- if (storeLocally != undefined) {
- setStoreLocally(storeLocally);
- }
- if (language != undefined) {
+ if (language) {
setLanguage(language);
}
- if (enableSlurReplacement != undefined) {
+ if (enableSlurReplacement) {
setEnableSlurReplacement(enableSlurReplacement);
+ if (enableSlurReplacement) {
+ console.log('HEREE');
+ setSelectedOption('replace');
+ }
}
- if (enableSlurMetadata != undefined) {
+ if (enableSlurMetadata) {
setEnableSlurMetadata(enableSlurMetadata);
+ if (enableSlurMetadata) {
+ console.log('HEREE META');
+ setSelectedOption('metadata');
+ }
+ }
+ if(!enableSlurMetadata && !enableSlurReplacement){
+ setSelectedOption('off')
}
}
}
@@ -92,10 +113,26 @@ export function Preferences() {
};
}, [user]);
- async function handleSlurReplacementAndSlurMetadata(enableSlurReplacement, enableSlurMetadata) {
+ useEffect(() => {
+ console.log('SELECTED OPTION: ', selectedOption);
+
+ if (selectedOption == 'replace') {
+ setEnableSlurReplacement(true);
+ setEnableSlurMetadata(false);
+ } else if (selectedOption == 'metadata') {
+ setEnableSlurReplacement(false);
+ setEnableSlurMetadata(true);
+ }else if (selectedOption == 'off') {
+ setEnableSlurReplacement(false);
+ setEnableSlurMetadata(false);
+ }
+ }, [selectedOption]);
+
+ async function handleSlurReplacementAndSlurMetadata(
+ enableSlurReplacement,
+ enableSlurMetadata
+ ) {
try {
-
-
const confirmed = window.confirm(
'This action requires a page reload. Do you want to continue?'
);
@@ -125,35 +162,41 @@ export function Preferences() {
async function changeEnableSlurReplacementOption(checked) {
console.log(checked);
- if(checked === true) setEnableSlurMetadata(false);
+ if (checked === true) setEnableSlurMetadata(false);
setEnableSlurReplacement(checked);
}
async function changeEnableSlurMetadataOption(checked) {
console.log(checked);
- if(checked === true) setEnableSlurReplacement(false);
+ if (checked === true) setEnableSlurReplacement(false);
setEnableSlurMetadata(checked);
}
async function clickSave(preference) {
+ // console.log("PREFERENCES ARE: ", preference)
const preferenceInLS = await getPreferenceData();
// alert(JSON.stringify({preferenceInLS, preference}))
try {
- const preferenceRemote = await savePreference(
- user.accessToken,
- preference
- );
+ if (user) {
+ const preferenceRemote = await savePreference(
+ user.accessToken,
+ preference
+ );
- await setPreferenceData({
- ...preferenceRemote.data,
- enable,
- enableML,
- storeLocally,
- language,
- enableSlurReplacement,
- enableSlurMetadata
- });
+ await setPreferenceData({
+ ...preferenceRemote.data,
+ language,
+ enableSlurReplacement,
+ enableSlurMetadata
+ });
+ } else {
+ await setPreferenceData({
+ language,
+ enableSlurReplacement,
+ enableSlurMetadata
+ });
+ }
const enableSlurReplacementChanged =
enableSlurReplacement !== preferenceInLS.enableSlurReplacement;
@@ -163,7 +206,10 @@ export function Preferences() {
if (enableSlurReplacementChanged || enableSlurMetadataChanged) {
console.log('enable val changed', enableSlurReplacementChanged);
- await handleSlurReplacementAndSlurMetadata(enableSlurReplacement, enableSlurMetadata);
+ await handleSlurReplacementAndSlurMetadata(
+ enableSlurReplacement,
+ enableSlurMetadata
+ );
}
showNotification({
@@ -185,30 +231,8 @@ export function Preferences() {
i18n.changeLanguage(langNameMap[option]);
}
- async function changeLocalStorageOption(checked) {
- setStoreLocally(checked);
- }
-
- // async function changeEnableMLOption(checked) {
- // setEnableMLOption(checked);
- // }
-
return (
- {/*
-
-
- Read Configuration Guide Here
-
- */}
- {/* setEnable(e.target.checked)}
- /> */}
{t('language')}
-
- changeLocalStorageOption(e.target.checked)}
- />
-
- {/*
- changeEnableMLOption(e.target.checked)}
- />
- */}
-
-
- changeEnableSlurReplacementOption(e.target.checked)
- }
- />
-
-
-
- changeEnableSlurMetadataOption(e.target.checked)
- }
- />
-
+ setSelectedOption(event.target.value)}
+ />
-
+
+
+
+ {/*
+ /> */}
- }
- type="email"
- disabled={!enable}
- component={TextInput}
- />
-
- {/*
- {t('friends')}
-
-
-
-
- }
- disabled={!enable}
- component={TextArea}
- /> */}
-
-
+ /> */}
);
}
+
+export function PreferencesSlurList() {
+ const navigate = useNavigate();
+ const [resetSlurs, setResetSlurs] = useState([]);
+ const [slurs, setSlurs] = useState([]);
+ const [displaySlurs, setDisplaySlurs] = useState([]);
+ const [input, setInput] = useState('');
+ const [error, setError] = useState('');
+ const { t, i18n } = useTranslation();
+ // const [localPreferences, setLocalPreferences] = useState(defaultValue);
+ const { user } = useContext(UserContext);
+ const [success, setSuccess] = useState('');
+ const { showNotification } = useContext(NotificationContext);
+
+ useEffect(() => {
+ async function getPrefsLocalStorage() {
+ try {
+ const preference = await getPreferenceData();
+ console.log('preference ', preference);
+ if (!ignore) {
+ // console.log({ preference });
+ // setLocalPreferences(preference);
+ let slurString = preference.slurList || '';
+ let slurArr = slurString == '' ? [] : slurString.split(',');
+ setSlurs(slurArr);
+ setDisplaySlurs(slurArr);
+ setResetSlurs(slurArr);
+ }
+ } catch (err) {
+ showNotification({
+ type: 'error',
+ message: t('message_error_preference_data_load')
+ });
+ // alert(err);
+ }
+ }
+
+ let ignore = false;
+ getPrefsLocalStorage();
+ setResetSlurs(slurs);
+ return () => {
+ ignore = true;
+ };
+ }, []);
+
+ useEffect(() => {
+ setError('');
+ setSuccess('');
+
+ if (input.trim() == '') {
+ setDisplaySlurs(slurs);
+ } else {
+ searchSlur(input);
+ }
+ }, [input]);
+
+ function searchSlur(input) {
+ filterSlur = slurs.filter((s) => s.includes(input));
+ setDisplaySlurs(filterSlur);
+ }
+
+ function addSlur(e) {
+ e.preventDefault();
+ setError('');
+ setSuccess('');
+
+ if (input.trim().length > 45) {
+ setError('Character limit exceeded. Please add a shorter word.');
+ return;
+ }
+ if (slurs.includes(input.trim())) {
+ setError('Slur already exists');
+ return;
+ }
+ console.log('Added Slur: ', input);
+ if (input) {
+ if (input.includes(',')) {
+ let slursArr = input
+ .split(',')
+ .map((s) => s.trim())
+ .filter((s) => !slurs.includes(s));
+ setSlurs([...slurs, ...slursArr]);
+ } else {
+ setSlurs([...slurs, input.trim()]);
+ }
+ }
+ setInput('');
+ }
+
+ function deleteSlur(slur) {
+ setSlurs((prevSlurs) => prevSlurs.filter((s) => s !== slur));
+ setDisplaySlurs((prevSlurs) => prevSlurs.filter((s) => s !== slur));
+ }
+
+ function resetAllSlurs() {
+ setError('');
+ setSuccess('');
+
+ if (slurs == resetSlurs) {
+ setError('No new slurs were added.');
+ return;
+ }
+
+ setSlurs(resetSlurs);
+ setDisplaySlurs(resetSlurs);
+ }
+
+ async function saveSlurs() {
+ setError('');
+ setSuccess('');
+
+ if (slurs == resetSlurs) {
+ setError('No new slurs were added.');
+ return;
+ }
+
+ try {
+ let preferenceInLS = await getPreferenceData();
+
+ preferenceInLS = { ...preferenceInLS, slurList: slurs.toString() };
+ let preferenceRemote = await savePreference(
+ user.accessToken,
+ preferenceInLS
+ );
+
+ await setPreferenceData({
+ ...preferenceInLS,
+ ...preferenceRemote.data
+ });
+
+ setResetSlurs(slurs);
+ // setSuccess("Saved Successfully!")
+ showNotification({
+ type: 'message',
+ message: t('message_ok_saved')
+ });
+ browserUtils.sendMessage('updateData', undefined);
+ } catch (error) {
+ console.error(error);
+ setError('Something went wrong while saving.');
+ }
+ }
+ return (
+
+
+ }
+ fill={false}
+ onClick={() => navigate('/preferences')}
+ />
+ Add to your personal block list
+
+
+
+ Add slurs
+
+
+ {error} {success}
+
+
+
+ {displaySlurs && displaySlurs.length > 0 ? (
+ displaySlurs.map((slur, key) => {
+ return (
+ deleteSlur(slur)}
+ />
+ );
+ })
+ ) : slurs && slurs.length > 0 ? (
+
+ Add "{input}" to your personal block list
+
+ ) : (
+
+ Add slurs to your personal block list
+
+ )}
+
+
+
+
+
+
+
+
+ );
+}
+
+function SlurChip({ slur, deleteSlur }) {
+ return (
+
+ {slur}
+
+ }
+ onClick={deleteSlur}
+ />
+
+
+ );
+}
+
+// import { useState, useEffect, useContext } from 'react';
+// import {
+// Box,
+// Form,
+// FormField,
+// TextInput,
+// TextArea,
+// Text,
+// Button,
+// Select,
+// CheckBox
+// } from 'grommet';
+// // import { HelpCircle } from 'react-feather';
+// import Api from '../pages/Api';
+// import repository from '../../repository';
+// import { useTranslation } from 'react-i18next';
+// import browserUtils from '../../chrome';
+// import { langNameMap } from '../atoms/language';
+// const { savePreference } = Api;
+// import { UserContext, NotificationContext } from '../atoms/AppContext';
+// import { userBrowserTabs } from '../../browser-compat';
+// const { setPreferenceData, getPreferenceData } = repository;
+
+// const defaultValue = {};
+
+// export function Preferences() {
+// const [localPreferences, setLocalPreferences] = useState(defaultValue);
+// const { user } = useContext(UserContext);
+// const { showNotification } = useContext(NotificationContext);
+// const [enable, setEnable] = useState(true);
+// const [enableML, setEnableMLOption] = useState(false);
+// const [enableSlurReplacement, setEnableSlurReplacement] = useState(true);
+// const [enableSlurMetadata, setEnableSlurMetadata] = useState(false);
+// const [storeLocally, setStoreLocally] = useState(true);
+// const [language, setLanguage] = useState('English');
+// const { t, i18n } = useTranslation();
+
+// // GET PREFERENCE FOR THIS USER FROM LS
+// useEffect(() => {
+// async function getPrefsLocalStorage() {
+// try {
+// const preference = await getPreferenceData();
+// console.log("preference " , preference)
+// if (!ignore) {
+// // console.log({ preference });
+// setLocalPreferences(preference);
+// if (
+// preference != undefined &&
+// Object.keys(preference).length != 0
+// ) {
+// const {
+// enable,
+// enableML,
+// storeLocally,
+// language,
+// enableSlurReplacement,
+// enableSlurMetadata
+// } = preference;
+// if (enable != undefined) {
+// setEnable(enable);
+// }
+// if (enableML != undefined) {
+// setEnableMLOption(enableML);
+// }
+// if (storeLocally != undefined) {
+// setStoreLocally(storeLocally);
+// }
+// if (language != undefined) {
+// setLanguage(language);
+// }
+// if (enableSlurReplacement != undefined) {
+// setEnableSlurReplacement(enableSlurReplacement);
+// }
+// if (enableSlurMetadata != undefined) {
+// setEnableSlurMetadata(enableSlurMetadata);
+// }
+// }
+// }
+// } catch (err) {
+// showNotification({
+// type: 'error',
+// message: t('message_error_preference_data_load')
+// });
+// // alert(err);
+// }
+// }
+
+// let ignore = false;
+// getPrefsLocalStorage();
+// return () => {
+// ignore = true;
+// };
+// }, [user]);
+
+// async function handleSlurReplacementAndSlurMetadata(enableSlurReplacement, enableSlurMetadata) {
+// try {
+
+// const confirmed = window.confirm(
+// 'This action requires a page reload. Do you want to continue?'
+// );
+// if (confirmed) {
+// const tabsCurrent = await userBrowserTabs.query({
+// active: true,
+// currentWindow: true
+// });
+// const tabId = tabsCurrent[0].id;
+
+// await setPreferenceData({
+// ...localPreferences,
+// enableSlurReplacement,
+// enableSlurMetadata
+// });
+
+// userBrowserTabs.sendMessage(tabId, {
+// type: 'ULI_ENABLE_SLUR_REPLACEMENT',
+// payload: enableSlurReplacement
+// });
+// userBrowserTabs.reload(tabId);
+// }
+// } catch (error) {
+// console.log(error);
+// }
+// }
+
+// async function changeEnableSlurReplacementOption(checked) {
+// console.log(checked);
+// if(checked === true) setEnableSlurMetadata(false);
+// setEnableSlurReplacement(checked);
+// }
+
+// async function changeEnableSlurMetadataOption(checked) {
+// console.log(checked);
+// if(checked === true) setEnableSlurReplacement(false);
+// setEnableSlurMetadata(checked);
+// }
+
+// async function clickSave(preference) {
+// const preferenceInLS = await getPreferenceData();
+// // alert(JSON.stringify({preferenceInLS, preference}))
+
+// try {
+// const preferenceRemote = await savePreference(
+// user.accessToken,
+// preference
+// );
+
+// await setPreferenceData({
+// ...preferenceRemote.data,
+// enable,
+// enableML,
+// storeLocally,
+// language,
+// enableSlurReplacement,
+// enableSlurMetadata
+// });
+
+// const enableSlurReplacementChanged =
+// enableSlurReplacement !== preferenceInLS.enableSlurReplacement;
+
+// const enableSlurMetadataChanged =
+// enableSlurMetadata !== preferenceInLS.enableSlurMetadata;
+
+// if (enableSlurReplacementChanged || enableSlurMetadataChanged) {
+// console.log('enable val changed', enableSlurReplacementChanged);
+// await handleSlurReplacementAndSlurMetadata(enableSlurReplacement, enableSlurMetadata);
+// }
+
+// showNotification({
+// type: 'message',
+// message: t('message_ok_saved')
+// });
+// browserUtils.sendMessage('updateData', undefined);
+// } catch (err) {
+// showNotification({
+// type: 'error',
+// message: t('message_error_preference_data_save')
+// });
+// console.log(err);
+// }
+// }
+
+// async function changeLanguage(option) {
+// setLanguage(option);
+// i18n.changeLanguage(langNameMap[option]);
+// }
+
+// async function changeLocalStorageOption(checked) {
+// setStoreLocally(checked);
+// }
+
+// // async function changeEnableMLOption(checked) {
+// // setEnableMLOption(checked);
+// // }
+
+// return (
+//
+// {/*
+//
+//
+// Read Configuration Guide Here
+//
+// */}
+// {/* setEnable(e.target.checked)}
+// /> */}
+//
+// {t('language')}
+//
+//
+// changeLocalStorageOption(e.target.checked)}
+// />
+//
+// {/*
+// changeEnableMLOption(e.target.checked)}
+// />
+// */}
+//
+//
+// changeEnableSlurReplacementOption(e.target.checked)
+// }
+// />
+//
+
+//
+//
+// changeEnableSlurMetadataOption(e.target.checked)
+// }
+// />
+//
+
+//
+//
+// }
+// type="email"
+// disabled={!enable}
+// component={TextInput}
+// />
+
+// {/*
+// {t('friends')}
+//
+//
+//
+//
+// }
+// disabled={!enable}
+// component={TextArea}
+// /> */}
+
+//
+// {t('your_slur_list')}
+//
+// }
+// disabled={!enable}
+// component={TextArea}
+// />
+
+//
+//
+
+// {/*
+//
+//
+// );
+// }
diff --git a/uli-community/.dockerignore b/uli-community/.dockerignore
new file mode 100644
index 00000000..61a73933
--- /dev/null
+++ b/uli-community/.dockerignore
@@ -0,0 +1,45 @@
+# This file excludes paths from the Docker build context.
+#
+# By default, Docker's build context includes all files (and folders) in the
+# current directory. Even if a file isn't copied into the container it is still sent to
+# the Docker daemon.
+#
+# There are multiple reasons to exclude files from the build context:
+#
+# 1. Prevent nested folders from being copied into the container (ex: exclude
+# /assets/node_modules when copying /assets)
+# 2. Reduce the size of the build context and improve build time (ex. /build, /deps, /doc)
+# 3. Avoid sending files containing sensitive information
+#
+# More information on using .dockerignore is available here:
+# https://docs.docker.com/engine/reference/builder/#dockerignore-file
+
+.dockerignore
+
+# Ignore git, but keep git HEAD and refs to access current commit hash if needed:
+#
+# $ cat .git/HEAD | awk '{print ".git/"$2}' | xargs cat
+# d0b8727759e1e0e7aa3d41707d12376e373d5ecc
+.git
+!.git/HEAD
+!.git/refs
+
+# Common development/test artifacts
+/cover/
+/doc/
+/test/
+/tmp/
+.elixir_ls
+
+# Mix artifacts
+/_build/
+/deps/
+*.ez
+
+# Generated on crash by the VM
+erl_crash.dump
+
+# Static artifacts - These should be fetched and built inside the Docker image
+/assets/node_modules/
+/priv/static/assets/
+/priv/static/cache_manifest.json
diff --git a/uli-community/.formatter.exs b/uli-community/.formatter.exs
new file mode 100644
index 00000000..ef8840ce
--- /dev/null
+++ b/uli-community/.formatter.exs
@@ -0,0 +1,6 @@
+[
+ import_deps: [:ecto, :ecto_sql, :phoenix],
+ subdirectories: ["priv/*/migrations"],
+ plugins: [Phoenix.LiveView.HTMLFormatter],
+ inputs: ["*.{heex,ex,exs}", "{config,lib,test}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"]
+]
diff --git a/uli-community/.gitignore b/uli-community/.gitignore
new file mode 100644
index 00000000..76cc325e
--- /dev/null
+++ b/uli-community/.gitignore
@@ -0,0 +1,37 @@
+# The directory Mix will write compiled artifacts to.
+/_build/
+
+# If you run "mix test --cover", coverage assets end up here.
+/cover/
+
+# The directory Mix downloads your dependencies sources to.
+/deps/
+
+# Where 3rd-party dependencies like ExDoc output generated docs.
+/doc/
+
+# Ignore .fetch files in case you like to edit your project deps locally.
+/.fetch
+
+# If the VM crashes, it generates a dump, let's ignore it too.
+erl_crash.dump
+
+# Also ignore archive artifacts (built via "mix archive.build").
+*.ez
+
+# Temporary files, for example, from tests.
+/tmp/
+
+# Ignore package tarball (built via "mix hex.build").
+tattle-*.tar
+
+# Ignore assets that are produced by build tools.
+/priv/static/assets/
+
+# Ignore digested assets cache.
+/priv/static/cache_manifest.json
+
+# In case you use Node.js/npm, you want to ignore these.
+npm-debug.log
+/assets/node_modules/
+
diff --git a/uli-community/LICENSE b/uli-community/LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/uli-community/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/uli-community/README.md b/uli-community/README.md
new file mode 100644
index 00000000..ca71de07
--- /dev/null
+++ b/uli-community/README.md
@@ -0,0 +1,104 @@
+# UliCommunity
+
+This project is a Phoenix template designed to streamline the setting up of a Phoenix application with built-in authentication and authorization. It supports authentication for both LiveView and non-LiveView components. Additionally, it includes an API server for generating authentication tokens and performing actions securely using a valid token.
+
+**Note:** The name of this Phoenix project (the name that was used in the generator while creating the project) is "uli_community"
+
+## Table of Content
+
+- [Start Development](#start-development)
+- [Authentication in Web App itself](#authentication-in-web-app-itself)
+ * [Differences between the Authentication with and without the liveview](#differences-between-the-authentication-with-and-without-the-liveview)
+ * [Adjustments to make both kinds of Authentications work](#adjustments-to-make-both-kinds-of-authentications-work)
+ + [Changing the Scope of non-liveview routes](#changing-the-scope-of-non-liveview-routes)
+- [Authentication with Token](#authentication-with-token)
+- [Authorization](#authorization)
+- [Access Token](#access-token)
+
+## Start Development
+
+To start your Phoenix server:
+
+ * Run `docker compose up`
+ * Run `mix setup` to install and setup dependencies
+ * Start Phoenix endpoint with `mix phx.server` or inside IEx with `iex -S mix phx.server`
+
+Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
+
+Ready to run in production? Please [check the deployment guides](https://hexdocs.pm/phoenix/deployment.html).
+
+## Authentication in Web App itself
+
+To generate template code for authentication, phoenix provides a command `mix phx.gen.auth`. This command provides an option to generate code with either live-view or without live-view.
+
+In this project, we wanted to keep both kinds of authentication options as a proof of concept. So we first generated the template code with the normal (with no live-view) option and then generated it with the live-view option.
+
+### Differences between the Authentication with and without the liveview
+
+- The code for non-liveview generated all the relevant routes and their respective controllers.
+- The code for liveview generated routes for the liveview templates with their respective controllers inside `/live` folder.
+- The generator did not overwrite the routes, it just added the new routes below the old ones with different macros (live instead of REST macros). However, the route addresses were the same for both the generated routes. Ex- both had `/users/log_in` addresses for their login routes.
+- For login, they both use the `UserSessionController` controller; because of this, the generator for liveview overwrote the code inside this controller.
+- Using the generator generated the same migration file to create the Accounts table twice. (In case of overwriting a file, the generator always asks for every file).
+
+### Adjustments to make both kinds of Authentications work
+
+- The following points are only for authentication routes.
+
+#### Changing the Scope of non-liveview routes
+- As the route addresses were the same in both cases, the `scope` for the non-liveview routes was changed from `"/"` to `"/nolive"`.
+- By default, on clicking the registration and login buttons on the homepage, everything will render the liveview templates. To access the similar route for the no-liveview templates prepend `/nolive` to the route.
+ - **NOTE:** While accessing the no-liveview routes, please make sure that the actions the non-liveview templates are calling are also the ones with `/nolive` routes.
+ - For example- the `/nolive/users/log_in` route renders the `/controllers/user_session_html/new.html.heex` template, which is a template that renders the login form. So in order to log through the no-liveview way, in the form-action the route has to be changed from `/users/log_in` to `/nolive/users/log_in` to make everything work with no errors (as the routes not starting with "nolive" are liveview routes.)
+ - This has already been implemented for the "login" route, but for other similar routes, please check this before testing.
+
+ #### Changes in UserSessionController
+ - To address the problem of the same `UserSessionController` for both the login routes (liveview and non-liveview), a new `UserSessionLiveController` is created for the liveview login.
+ - The `UserSessionController` is now only getting used for the no-liveview routes.
+
+ #### For Migration files
+ - As two migration files were the same, one of them was deleted.
+
+## Authentication with Token
+
+This post was referred to while implementing the token functionality: https://dev.to/onpointvn/implement-jwt-authentication-with-phoenix-token-n58
+
+The Token-based authentication is implemented to use the project as a service.
+
+- A separate `/UliCommunity/api` context is created. Inside it, there is the `Token` module.
+- The Token module uses `Phoenix.Token` to havea sign and verify token function.
+- `Phoenix.Token` is a JSON Web Token.
+- For this functionality, separate routes with the scope `/api` are created.
+- A new `AuthenticateApi` plug was also created to authenticate the JWT token.
+- Currently, there are only two routes for this functionality. One is `/api/auth/login` and another is `/api/auth/hi`.
+- The login route has nothing to do with login. It is an API endpoint through which users can receive their token in response if they send a request to this route with the right credentials. The controller for that is `SessionControllerApi`.
+- The `"/hi"` route is just a route to test if the authentication is working properly or not. Users can send a Get request to this route with "Bearer AUTH_TOKEN" in the Authentication header, to receive a simple message.
+- We can use the API context to create more functions and routes to provide different API services to the users.
+
+## Authorization
+
+- This article was referred to implement the authorization: https://hashrocket.com/blog/posts/authorization-in-phoenix-liveview
+- Authorization functionality is implemented with currently two roles "user" and "admin", for a proof of concept.
+- The default role of the user is "admin". Currently, in order to change the role of a user, we have to update it in the database itself.
+- Currently, we are only implementing the route-based authorization, so if a user with the role "user" tries to access an admin route, that would not be allowed.
+- A new context for Authorization is created in `/uli_comminity/authorization`.
+- Here we can add more routes that need to implement the authorization.
+- Other changes include changes in the router to include `on_mount` functions and changes in the `user_auth` module to create a new `on_mount` function.
+
+## Access Token
+
+This access token functionality is different from the above mentioned auth token. The above mentioned auth tokens are generated from the API call by passing login creds in the request itself and then can be used to make the further API calls. The generated token is a JWT token which just stores the user id (from the User schema) that created the token.
+
+This Access Token is also a JWT token, but it is generated by a registered user inside the application. The token itself is not getting stored anywhere for secrecy but all the information related to that access token is getting stored inside a "Access_Token" table. Each entry has properties of `token_id`, `token_name`, `access_level`, `expiry`, `created_by_user`. The token hashes the `token_id` property, which gets checked and used to retrieve the relevent token entry, while any API call would be made.
+
+- A new `UliCommunity.Api.AccessToken` Schema was created inside the api context.
+- Access Tokens can be generated in the `/gentoken` route.
+- In this page, the users would be able to see the token generated by them.
+- The users would be able to set the access level based on their own access levels. If a user is "Admin", the generated token can have both "Admin" and "User" access levels. But if the user is "User", the generated token can only have the "User" access level.
+- To implement this, a new plug has been created, `authenticate_access_token`.
+- A new scope is also created, `/api/accesstoken`. This scope will be responsible for accessing the routes though the generated access_token. The name of the scope can be changed if needed in the future.
+- To test the access token, a dummy route `/api/accesstoken/hi` is created. We can test the generated access token by sending a `get` request to this route with the `Authorization` header set to "Bearer 'Access Token' ".
+- If the token is valid, a json response with a hi message would be received.
+- Other minor changes include:
+ - Created a new modal component to show the generated token (the one in the core-components was not used because that modal gets closed whenever we click anywhere on the screen. We don't want that while showing one-time generated token that can never be seen again).
+ - Minor addition in the `assets/js/app.js` to implement copy to clipboard functionality.
\ No newline at end of file
diff --git a/uli-community/assets/css/app.css b/uli-community/assets/css/app.css
new file mode 100644
index 00000000..378c8f90
--- /dev/null
+++ b/uli-community/assets/css/app.css
@@ -0,0 +1,5 @@
+@import "tailwindcss/base";
+@import "tailwindcss/components";
+@import "tailwindcss/utilities";
+
+/* This file is for your main application CSS */
diff --git a/uli-community/assets/js/app.js b/uli-community/assets/js/app.js
new file mode 100644
index 00000000..878e1fef
--- /dev/null
+++ b/uli-community/assets/js/app.js
@@ -0,0 +1,56 @@
+// If you want to use Phoenix channels, run `mix help phx.gen.channel`
+// to get started and then uncomment the line below.
+// import "./user_socket.js"
+
+// You can include dependencies in two ways.
+//
+// The simplest option is to put them in assets/vendor and
+// import them using relative paths:
+//
+// import "../vendor/some-package.js"
+//
+// Alternatively, you can `npm install some-package --prefix assets` and import
+// them using a path starting with the package name:
+//
+// import "some-package"
+//
+
+// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
+import "phoenix_html";
+// Establish Phoenix Socket and LiveView configuration.
+import { Socket } from "phoenix";
+import { LiveSocket } from "phoenix_live_view";
+import topbar from "../vendor/topbar";
+
+let csrfToken = document
+ .querySelector("meta[name='csrf-token']")
+ .getAttribute("content");
+let liveSocket = new LiveSocket("/live", Socket, {
+ longPollFallbackMs: 2500,
+ params: { _csrf_token: csrfToken },
+});
+
+// Show progress bar on live navigation and form submits
+topbar.config({ barColors: { 0: "#29d" }, shadowColor: "rgba(0, 0, 0, .3)" });
+window.addEventListener("phx:page-loading-start", (_info) => topbar.show(300));
+window.addEventListener("phx:page-loading-stop", (_info) => topbar.hide());
+
+// connect if there are any LiveViews on the page
+liveSocket.connect();
+
+// expose liveSocket on window for web console debug logs and latency simulation:
+// >> liveSocket.enableDebug()
+// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
+// >> liveSocket.disableLatencySim()
+window.liveSocket = liveSocket;
+
+window.addEventListener("phx:copy", (event) => {
+ let text = event.target.innerText;
+ navigator.clipboard.writeText(text).then(() => {
+ let copyBtn = document.getElementById("copy-button");
+ copyBtn.innerHTML = "Copied! 📋";
+ setTimeout(() => {
+ copyBtn.innerHTML = "Copy 📋";
+ }, 1000);
+ });
+});
diff --git a/uli-community/assets/tailwind.config.js b/uli-community/assets/tailwind.config.js
new file mode 100644
index 00000000..f01cd535
--- /dev/null
+++ b/uli-community/assets/tailwind.config.js
@@ -0,0 +1,74 @@
+// See the Tailwind configuration guide for advanced usage
+// https://tailwindcss.com/docs/configuration
+
+const plugin = require("tailwindcss/plugin")
+const fs = require("fs")
+const path = require("path")
+
+module.exports = {
+ content: [
+ "./js/**/*.js",
+ "../lib/uli_community_web.ex",
+ "../lib/uli_community_web/**/*.*ex"
+ ],
+ theme: {
+ extend: {
+ colors: {
+ brand: "#FD4F00",
+ }
+ },
+ },
+ plugins: [
+ require("@tailwindcss/forms"),
+ // Allows prefixing tailwind classes with LiveView classes to add rules
+ // only when LiveView classes are applied, for example:
+ //
+ //
+ //
+ plugin(({ addVariant }) => addVariant("phx-click-loading", [".phx-click-loading&", ".phx-click-loading &"])),
+ plugin(({ addVariant }) => addVariant("phx-submit-loading", [".phx-submit-loading&", ".phx-submit-loading &"])),
+ plugin(({ addVariant }) => addVariant("phx-change-loading", [".phx-change-loading&", ".phx-change-loading &"])),
+
+ // Embeds Heroicons (https://heroicons.com) into your app.css bundle
+ // See your `CoreComponents.icon/1` for more information.
+ //
+ plugin(function ({ matchComponents, theme }) {
+ let iconsDir = path.join(__dirname, "../deps/heroicons/optimized")
+ let values = {}
+ let icons = [
+ ["", "/24/outline"],
+ ["-solid", "/24/solid"],
+ ["-mini", "/20/solid"],
+ ["-micro", "/16/solid"]
+ ]
+ icons.forEach(([suffix, dir]) => {
+ fs.readdirSync(path.join(iconsDir, dir)).forEach(file => {
+ let name = path.basename(file, ".svg") + suffix
+ values[name] = { name, fullPath: path.join(iconsDir, dir, file) }
+ })
+ })
+ matchComponents({
+ "hero": ({ name, fullPath }) => {
+ let content = fs.readFileSync(fullPath).toString().replace(/\r?\n|\r/g, "")
+ let size = theme("spacing.6")
+ if (name.endsWith("-mini")) {
+ size = theme("spacing.5")
+ } else if (name.endsWith("-micro")) {
+ size = theme("spacing.4")
+ }
+ return {
+ [`--hero-${name}`]: `url('data:image/svg+xml;utf8,${content}')`,
+ "-webkit-mask": `var(--hero-${name})`,
+ "mask": `var(--hero-${name})`,
+ "mask-repeat": "no-repeat",
+ "background-color": "currentColor",
+ "vertical-align": "middle",
+ "display": "inline-block",
+ "width": size,
+ "height": size
+ }
+ }
+ }, { values })
+ })
+ ]
+}
diff --git a/uli-community/assets/vendor/topbar.js b/uli-community/assets/vendor/topbar.js
new file mode 100644
index 00000000..41957274
--- /dev/null
+++ b/uli-community/assets/vendor/topbar.js
@@ -0,0 +1,165 @@
+/**
+ * @license MIT
+ * topbar 2.0.0, 2023-02-04
+ * https://buunguyen.github.io/topbar
+ * Copyright (c) 2021 Buu Nguyen
+ */
+(function (window, document) {
+ "use strict";
+
+ // https://gist.github.com/paulirish/1579671
+ (function () {
+ var lastTime = 0;
+ var vendors = ["ms", "moz", "webkit", "o"];
+ for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
+ window.requestAnimationFrame =
+ window[vendors[x] + "RequestAnimationFrame"];
+ window.cancelAnimationFrame =
+ window[vendors[x] + "CancelAnimationFrame"] ||
+ window[vendors[x] + "CancelRequestAnimationFrame"];
+ }
+ if (!window.requestAnimationFrame)
+ window.requestAnimationFrame = function (callback, element) {
+ var currTime = new Date().getTime();
+ var timeToCall = Math.max(0, 16 - (currTime - lastTime));
+ var id = window.setTimeout(function () {
+ callback(currTime + timeToCall);
+ }, timeToCall);
+ lastTime = currTime + timeToCall;
+ return id;
+ };
+ if (!window.cancelAnimationFrame)
+ window.cancelAnimationFrame = function (id) {
+ clearTimeout(id);
+ };
+ })();
+
+ var canvas,
+ currentProgress,
+ showing,
+ progressTimerId = null,
+ fadeTimerId = null,
+ delayTimerId = null,
+ addEvent = function (elem, type, handler) {
+ if (elem.addEventListener) elem.addEventListener(type, handler, false);
+ else if (elem.attachEvent) elem.attachEvent("on" + type, handler);
+ else elem["on" + type] = handler;
+ },
+ options = {
+ autoRun: true,
+ barThickness: 3,
+ barColors: {
+ 0: "rgba(26, 188, 156, .9)",
+ ".25": "rgba(52, 152, 219, .9)",
+ ".50": "rgba(241, 196, 15, .9)",
+ ".75": "rgba(230, 126, 34, .9)",
+ "1.0": "rgba(211, 84, 0, .9)",
+ },
+ shadowBlur: 10,
+ shadowColor: "rgba(0, 0, 0, .6)",
+ className: null,
+ },
+ repaint = function () {
+ canvas.width = window.innerWidth;
+ canvas.height = options.barThickness * 5; // need space for shadow
+
+ var ctx = canvas.getContext("2d");
+ ctx.shadowBlur = options.shadowBlur;
+ ctx.shadowColor = options.shadowColor;
+
+ var lineGradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
+ for (var stop in options.barColors)
+ lineGradient.addColorStop(stop, options.barColors[stop]);
+ ctx.lineWidth = options.barThickness;
+ ctx.beginPath();
+ ctx.moveTo(0, options.barThickness / 2);
+ ctx.lineTo(
+ Math.ceil(currentProgress * canvas.width),
+ options.barThickness / 2
+ );
+ ctx.strokeStyle = lineGradient;
+ ctx.stroke();
+ },
+ createCanvas = function () {
+ canvas = document.createElement("canvas");
+ var style = canvas.style;
+ style.position = "fixed";
+ style.top = style.left = style.right = style.margin = style.padding = 0;
+ style.zIndex = 100001;
+ style.display = "none";
+ if (options.className) canvas.classList.add(options.className);
+ document.body.appendChild(canvas);
+ addEvent(window, "resize", repaint);
+ },
+ topbar = {
+ config: function (opts) {
+ for (var key in opts)
+ if (options.hasOwnProperty(key)) options[key] = opts[key];
+ },
+ show: function (delay) {
+ if (showing) return;
+ if (delay) {
+ if (delayTimerId) return;
+ delayTimerId = setTimeout(() => topbar.show(), delay);
+ } else {
+ showing = true;
+ if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId);
+ if (!canvas) createCanvas();
+ canvas.style.opacity = 1;
+ canvas.style.display = "block";
+ topbar.progress(0);
+ if (options.autoRun) {
+ (function loop() {
+ progressTimerId = window.requestAnimationFrame(loop);
+ topbar.progress(
+ "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2)
+ );
+ })();
+ }
+ }
+ },
+ progress: function (to) {
+ if (typeof to === "undefined") return currentProgress;
+ if (typeof to === "string") {
+ to =
+ (to.indexOf("+") >= 0 || to.indexOf("-") >= 0
+ ? currentProgress
+ : 0) + parseFloat(to);
+ }
+ currentProgress = to > 1 ? 1 : to;
+ repaint();
+ return currentProgress;
+ },
+ hide: function () {
+ clearTimeout(delayTimerId);
+ delayTimerId = null;
+ if (!showing) return;
+ showing = false;
+ if (progressTimerId != null) {
+ window.cancelAnimationFrame(progressTimerId);
+ progressTimerId = null;
+ }
+ (function loop() {
+ if (topbar.progress("+.1") >= 1) {
+ canvas.style.opacity -= 0.05;
+ if (canvas.style.opacity <= 0.05) {
+ canvas.style.display = "none";
+ fadeTimerId = null;
+ return;
+ }
+ }
+ fadeTimerId = window.requestAnimationFrame(loop);
+ })();
+ },
+ };
+
+ if (typeof module === "object" && typeof module.exports === "object") {
+ module.exports = topbar;
+ } else if (typeof define === "function" && define.amd) {
+ define(function () {
+ return topbar;
+ });
+ } else {
+ this.topbar = topbar;
+ }
+}.call(this, window, document));
diff --git a/uli-community/config/config.exs b/uli-community/config/config.exs
new file mode 100644
index 00000000..831a39f5
--- /dev/null
+++ b/uli-community/config/config.exs
@@ -0,0 +1,66 @@
+# This file is responsible for configuring your application
+# and its dependencies with the aid of the Config module.
+#
+# This configuration file is loaded before any dependency and
+# is restricted to this project.
+
+# General application configuration
+import Config
+
+config :uli_community,
+ ecto_repos: [UliCommunity.Repo],
+ generators: [timestamp_type: :utc_datetime]
+
+# Configures the endpoint
+config :uli_community, UliCommunityWeb.Endpoint,
+ url: [host: "localhost"],
+ adapter: Bandit.PhoenixAdapter,
+ render_errors: [
+ formats: [html: UliCommunityWeb.ErrorHTML, json: UliCommunityWeb.ErrorJSON],
+ layout: false
+ ],
+ pubsub_server: UliCommunity.PubSub,
+ live_view: [signing_salt: "4Xf27Zts"]
+
+# Configures the mailer
+#
+# By default it uses the "Local" adapter which stores the emails
+# locally. You can see the emails in your browser, at "/dev/mailbox".
+#
+# For production it's recommended to configure a different adapter
+# at the `config/runtime.exs`.
+config :uli_community, UliCommunity.Mailer, adapter: Swoosh.Adapters.Local
+
+# Configure esbuild (the version is required)
+config :esbuild,
+ version: "0.17.11",
+ uli_community: [
+ args:
+ ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
+ cd: Path.expand("../assets", __DIR__),
+ env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
+ ]
+
+# Configure tailwind (the version is required)
+config :tailwind,
+ version: "3.4.3",
+ uli_community: [
+ args: ~w(
+ --config=tailwind.config.js
+ --input=css/app.css
+ --output=../priv/static/assets/app.css
+ ),
+ cd: Path.expand("../assets", __DIR__)
+ ]
+
+# Configures Elixir's Logger
+config :logger, :console,
+ format: "$time $metadata[$level] $message\n",
+ metadata: [:request_id]
+
+# Use Jason for JSON parsing in Phoenix
+config :phoenix, :json_library, Jason
+
+# Import environment specific config. This must remain at the bottom
+# of this file so it overrides the configuration defined above.
+import_config "#{config_env()}.exs"
diff --git a/uli-community/config/dev.exs b/uli-community/config/dev.exs
new file mode 100644
index 00000000..24ee0791
--- /dev/null
+++ b/uli-community/config/dev.exs
@@ -0,0 +1,85 @@
+import Config
+
+# Configure your database
+config :uli_community, UliCommunity.Repo,
+ username: "uli_community",
+ password: "weak_password",
+ hostname: "localhost",
+ database: "uli_community_dev",
+ stacktrace: true,
+ show_sensitive_data_on_connection_error: true,
+ pool_size: 10
+
+# For development, we disable any cache and enable
+# debugging and code reloading.
+#
+# The watchers configuration can be used to run external
+# watchers to your application. For example, we can use it
+# to bundle .js and .css sources.
+config :uli_community, UliCommunityWeb.Endpoint,
+ # Binding to loopback ipv4 address prevents access from other machines.
+ # Change to `ip: {0, 0, 0, 0}` to allow access from other machines.
+ http: [ip: {127, 0, 0, 1}, port: 4000],
+ check_origin: false,
+ code_reloader: true,
+ debug_errors: true,
+ secret_key_base: "FwQCh6bBCjDs/SDbbTonAf+Pfk5qaUEBFU7WqW0J7oZIlrER2Zr3z8reoS4Pxojh",
+ watchers: [
+ esbuild: {Esbuild, :install_and_run, [:uli_community, ~w(--sourcemap=inline --watch)]},
+ tailwind: {Tailwind, :install_and_run, [:uli_community, ~w(--watch)]}
+ ]
+
+# ## SSL Support
+#
+# In order to use HTTPS in development, a self-signed
+# certificate can be generated by running the following
+# Mix task:
+#
+# mix phx.gen.cert
+#
+# Run `mix help phx.gen.cert` for more information.
+#
+# The `http:` config above can be replaced with:
+#
+# https: [
+# port: 4001,
+# cipher_suite: :strong,
+# keyfile: "priv/cert/selfsigned_key.pem",
+# certfile: "priv/cert/selfsigned.pem"
+# ],
+#
+# If desired, both `http:` and `https:` keys can be
+# configured to run both http and https servers on
+# different ports.
+
+# Watch static and templates for browser reloading.
+config :uli_community, UliCommunityWeb.Endpoint,
+ live_reload: [
+ patterns: [
+ ~r"priv/static/(?!uploads/).*(js|css|png|jpeg|jpg|gif|svg)$",
+ ~r"priv/gettext/.*(po)$",
+ ~r"lib/uli_community_web/(controllers|live|components)/.*(ex|heex)$"
+ ]
+ ]
+
+# Enable dev routes for dashboard and mailbox
+config :uli_community, dev_routes: true
+
+# Do not include metadata nor timestamps in development logs
+config :logger, :console, format: "[$level] $message\n"
+
+# Set a higher stacktrace during development. Avoid configuring such
+# in production as building large stacktraces may be expensive.
+config :phoenix, :stacktrace_depth, 20
+
+# Initialize plugs at runtime for faster development compilation
+config :phoenix, :plug_init_mode, :runtime
+
+config :phoenix_live_view,
+ # Include HEEx debug annotations as HTML comments in rendered markup
+ debug_heex_annotations: true,
+ # Enable helpful, but potentially expensive runtime checks
+ enable_expensive_runtime_checks: true
+
+# Disable swoosh api client as it is only required for production adapters.
+config :swoosh, :api_client, false
diff --git a/uli-community/config/prod.exs b/uli-community/config/prod.exs
new file mode 100644
index 00000000..ad767b42
--- /dev/null
+++ b/uli-community/config/prod.exs
@@ -0,0 +1,21 @@
+import Config
+
+# Note we also include the path to a cache manifest
+# containing the digested version of static files. This
+# manifest is generated by the `mix assets.deploy` task,
+# which you should run after static files are built and
+# before starting your production server.
+config :uli_community, UliCommunityWeb.Endpoint,
+ cache_static_manifest: "priv/static/cache_manifest.json"
+
+# Configures Swoosh API Client
+config :swoosh, api_client: Swoosh.ApiClient.Finch, finch_name: UliCommunity.Finch
+
+# Disable Swoosh Local Memory Storage
+config :swoosh, local: false
+
+# Do not print debug messages in production
+config :logger, level: :info
+
+# Runtime production configuration, including reading
+# of environment variables, is done on config/runtime.exs.
diff --git a/uli-community/config/runtime.exs b/uli-community/config/runtime.exs
new file mode 100644
index 00000000..4c4dba1e
--- /dev/null
+++ b/uli-community/config/runtime.exs
@@ -0,0 +1,117 @@
+import Config
+
+# config/runtime.exs is executed for all environments, including
+# during releases. It is executed after compilation and before the
+# system starts, so it is typically used to load production configuration
+# and secrets from environment variables or elsewhere. Do not define
+# any compile-time configuration in here, as it won't be applied.
+# The block below contains prod specific runtime configuration.
+
+# ## Using releases
+#
+# If you use `mix release`, you need to explicitly enable the server
+# by passing the PHX_SERVER=true when you start it:
+#
+# PHX_SERVER=true bin/uli_community start
+#
+# Alternatively, you can use `mix phx.gen.release` to generate a `bin/server`
+# script that automatically sets the env var above.
+if System.get_env("PHX_SERVER") do
+ config :uli_community, UliCommunityWeb.Endpoint, server: true
+end
+
+if config_env() == :prod do
+ database_url =
+ System.get_env("DATABASE_URL") ||
+ raise """
+ environment variable DATABASE_URL is missing.
+ For example: ecto://USER:PASS@HOST/DATABASE
+ """
+
+ maybe_ipv6 = if System.get_env("ECTO_IPV6") in ~w(true 1), do: [:inet6], else: []
+
+ config :uli_community, UliCommunity.Repo,
+ # ssl: true,
+ url: database_url,
+ pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
+ socket_options: maybe_ipv6
+
+ # The secret key base is used to sign/encrypt cookies and other secrets.
+ # A default value is used in config/dev.exs and config/test.exs but you
+ # want to use a different value for prod and you most likely don't want
+ # to check this value into version control, so we use an environment
+ # variable instead.
+ secret_key_base =
+ System.get_env("SECRET_KEY_BASE") ||
+ raise """
+ environment variable SECRET_KEY_BASE is missing.
+ You can generate one by calling: mix phx.gen.secret
+ """
+
+ host = System.get_env("PHX_HOST") || "example.com"
+ port = String.to_integer(System.get_env("PORT") || "4000")
+
+ config :uli_community, :dns_cluster_query, System.get_env("DNS_CLUSTER_QUERY")
+
+ config :uli_community, UliCommunityWeb.Endpoint,
+ url: [host: host, port: 443, scheme: "https"],
+ http: [
+ # Enable IPv6 and bind on all interfaces.
+ # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
+ # See the documentation on https://hexdocs.pm/bandit/Bandit.html#t:options/0
+ # for details about using IPv6 vs IPv4 and loopback vs public addresses.
+ ip: {0, 0, 0, 0, 0, 0, 0, 0},
+ port: port
+ ],
+ secret_key_base: secret_key_base
+
+ # ## SSL Support
+ #
+ # To get SSL working, you will need to add the `https` key
+ # to your endpoint configuration:
+ #
+ # config :uli_community, UliCommunityWeb.Endpoint,
+ # https: [
+ # ...,
+ # port: 443,
+ # cipher_suite: :strong,
+ # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
+ # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
+ # ]
+ #
+ # The `cipher_suite` is set to `:strong` to support only the
+ # latest and more secure SSL ciphers. This means old browsers
+ # and clients may not be supported. You can set it to
+ # `:compatible` for wider support.
+ #
+ # `:keyfile` and `:certfile` expect an absolute path to the key
+ # and cert in disk or a relative path inside priv, for example
+ # "priv/ssl/server.key". For all supported SSL configuration
+ # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
+ #
+ # We also recommend setting `force_ssl` in your config/prod.exs,
+ # ensuring no data is ever sent via http, always redirecting to https:
+ #
+ # config :uli_community, UliCommunityWeb.Endpoint,
+ # force_ssl: [hsts: true]
+ #
+ # Check `Plug.SSL` for all available options in `force_ssl`.
+
+ # ## Configuring the mailer
+ #
+ # In production you need to configure the mailer to use a different adapter.
+ # Also, you may need to configure the Swoosh API client of your choice if you
+ # are not using SMTP. Here is an example of the configuration:
+ #
+ # config :uli_community, UliCommunity.Mailer,
+ # adapter: Swoosh.Adapters.Mailgun,
+ # api_key: System.get_env("MAILGUN_API_KEY"),
+ # domain: System.get_env("MAILGUN_DOMAIN")
+ #
+ # For this example you need include a HTTP client required by Swoosh API client.
+ # Swoosh supports Hackney and Finch out of the box:
+ #
+ # config :swoosh, :api_client, Swoosh.ApiClient.Hackney
+ #
+ # See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.
+end
diff --git a/uli-community/config/test.exs b/uli-community/config/test.exs
new file mode 100644
index 00000000..aa2e1e49
--- /dev/null
+++ b/uli-community/config/test.exs
@@ -0,0 +1,40 @@
+import Config
+
+# Only in tests, remove the complexity from the password hashing algorithm
+config :bcrypt_elixir, :log_rounds, 1
+
+# Configure your database
+#
+# The MIX_TEST_PARTITION environment variable can be used
+# to provide built-in test partitioning in CI environment.
+# Run `mix help test` for more information.
+config :uli_community, UliCommunity.Repo,
+ username: "uli_community",
+ password: "weak_password",
+ hostname: "localhost",
+ database: "uli_community_test#{System.get_env("MIX_TEST_PARTITION")}",
+ pool: Ecto.Adapters.SQL.Sandbox,
+ pool_size: System.schedulers_online() * 2
+
+# We don't run a server during test. If one is required,
+# you can enable the server option below.
+config :uli_community, UliCommunityWeb.Endpoint,
+ http: [ip: {127, 0, 0, 1}, port: 4002],
+ secret_key_base: "UzRwVgVkiriZM7MRHm+TDKbg4FH0J9MaXpfE5tMwCZ6MfvFZP+jRcy2h9GcVA9I/",
+ server: false
+
+# In test we don't send emails
+config :uli_community, UliCommunity.Mailer, adapter: Swoosh.Adapters.Test
+
+# Disable swoosh api client as it is only required for production adapters
+config :swoosh, :api_client, false
+
+# Print only warnings and errors during test
+config :logger, level: :warning
+
+# Initialize plugs at runtime for faster test compilation
+config :phoenix, :plug_init_mode, :runtime
+
+# Enable helpful, but potentially expensive runtime checks
+config :phoenix_live_view,
+ enable_expensive_runtime_checks: true
diff --git a/uli-community/docker-compose.yml b/uli-community/docker-compose.yml
new file mode 100644
index 00000000..fa00244c
--- /dev/null
+++ b/uli-community/docker-compose.yml
@@ -0,0 +1,23 @@
+services:
+ db:
+ image: postgres:14.10
+ restart: always
+ environment:
+ - POSTGRES_USER=uli_community
+ - POSTGRES_PASSWORD=weak_password
+ - POSTGRES_DB=uli_community_dev
+ healthcheck:
+ test: [ "CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}" ]
+ interval: 1s
+ timeout: 5s
+ retries: 10
+ volumes:
+ - ~/data/uli_community_dev/postgres:/var/lib/postgresql/data
+ ports:
+ - 5432:5432
+
+ db_gui:
+ image: adminer
+ restart: always
+ ports:
+ - 8080:8080
diff --git a/uli-community/lib/uli_community.ex b/uli-community/lib/uli_community.ex
new file mode 100644
index 00000000..13e7ad2e
--- /dev/null
+++ b/uli-community/lib/uli_community.ex
@@ -0,0 +1,9 @@
+defmodule UliCommunity do
+ @moduledoc """
+ UliCommunity keeps the contexts that define your domain
+ and business logic.
+
+ Contexts are also responsible for managing your data, regardless
+ if it comes from the database, an external API or others.
+ """
+end
diff --git a/uli-community/lib/uli_community/accounts.ex b/uli-community/lib/uli_community/accounts.ex
new file mode 100644
index 00000000..aa1fb8fb
--- /dev/null
+++ b/uli-community/lib/uli_community/accounts.ex
@@ -0,0 +1,353 @@
+defmodule UliCommunity.Accounts do
+ @moduledoc """
+ The Accounts context.
+ """
+
+ import Ecto.Query, warn: false
+ alias UliCommunity.Repo
+
+ alias UliCommunity.Accounts.{User, UserToken, UserNotifier}
+
+ ## Database getters
+
+ @doc """
+ Gets a user by email.
+
+ ## Examples
+
+ iex> get_user_by_email("foo@example.com")
+ %User{}
+
+ iex> get_user_by_email("unknown@example.com")
+ nil
+
+ """
+ def get_user_by_email(email) when is_binary(email) do
+ Repo.get_by(User, email: email)
+ end
+
+ @doc """
+ Gets a user by email and password.
+
+ ## Examples
+
+ iex> get_user_by_email_and_password("foo@example.com", "correct_password")
+ %User{}
+
+ iex> get_user_by_email_and_password("foo@example.com", "invalid_password")
+ nil
+
+ """
+ def get_user_by_email_and_password(email, password)
+ when is_binary(email) and is_binary(password) do
+ user = Repo.get_by(User, email: email)
+ if User.valid_password?(user, password), do: user
+ end
+
+ @doc """
+ Gets a single user.
+
+ Raises `Ecto.NoResultsError` if the User does not exist.
+
+ ## Examples
+
+ iex> get_user!(123)
+ %User{}
+
+ iex> get_user!(456)
+ ** (Ecto.NoResultsError)
+
+ """
+ def get_user!(id), do: Repo.get!(User, id)
+
+ ## User registration
+
+ @doc """
+ Registers a user.
+
+ ## Examples
+
+ iex> register_user(%{field: value})
+ {:ok, %User{}}
+
+ iex> register_user(%{field: bad_value})
+ {:error, %Ecto.Changeset{}}
+
+ """
+ def register_user(attrs) do
+ %User{}
+ |> User.registration_changeset(attrs)
+ |> Repo.insert()
+ end
+
+ @doc """
+ Returns an `%Ecto.Changeset{}` for tracking user changes.
+
+ ## Examples
+
+ iex> change_user_registration(user)
+ %Ecto.Changeset{data: %User{}}
+
+ """
+ def change_user_registration(%User{} = user, attrs \\ %{}) do
+ User.registration_changeset(user, attrs, hash_password: false, validate_email: false)
+ end
+
+ ## Settings
+
+ @doc """
+ Returns an `%Ecto.Changeset{}` for changing the user email.
+
+ ## Examples
+
+ iex> change_user_email(user)
+ %Ecto.Changeset{data: %User{}}
+
+ """
+ def change_user_email(user, attrs \\ %{}) do
+ User.email_changeset(user, attrs, validate_email: false)
+ end
+
+ @doc """
+ Emulates that the email will change without actually changing
+ it in the database.
+
+ ## Examples
+
+ iex> apply_user_email(user, "valid password", %{email: ...})
+ {:ok, %User{}}
+
+ iex> apply_user_email(user, "invalid password", %{email: ...})
+ {:error, %Ecto.Changeset{}}
+
+ """
+ def apply_user_email(user, password, attrs) do
+ user
+ |> User.email_changeset(attrs)
+ |> User.validate_current_password(password)
+ |> Ecto.Changeset.apply_action(:update)
+ end
+
+ @doc """
+ Updates the user email using the given token.
+
+ If the token matches, the user email is updated and the token is deleted.
+ The confirmed_at date is also updated to the current time.
+ """
+ def update_user_email(user, token) do
+ context = "change:#{user.email}"
+
+ with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
+ %UserToken{sent_to: email} <- Repo.one(query),
+ {:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do
+ :ok
+ else
+ _ -> :error
+ end
+ end
+
+ defp user_email_multi(user, email, context) do
+ changeset =
+ user
+ |> User.email_changeset(%{email: email})
+ |> User.confirm_changeset()
+
+ Ecto.Multi.new()
+ |> Ecto.Multi.update(:user, changeset)
+ |> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, [context]))
+ end
+
+ @doc ~S"""
+ Delivers the update email instructions to the given user.
+
+ ## Examples
+
+ iex> deliver_user_update_email_instructions(user, current_email, &url(~p"/users/settings/confirm_email/#{&1}"))
+ {:ok, %{to: ..., body: ...}}
+
+ """
+ def deliver_user_update_email_instructions(%User{} = user, current_email, update_email_url_fun)
+ when is_function(update_email_url_fun, 1) do
+ {encoded_token, user_token} = UserToken.build_email_token(user, "change:#{current_email}")
+
+ Repo.insert!(user_token)
+ UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token))
+ end
+
+ @doc """
+ Returns an `%Ecto.Changeset{}` for changing the user password.
+
+ ## Examples
+
+ iex> change_user_password(user)
+ %Ecto.Changeset{data: %User{}}
+
+ """
+ def change_user_password(user, attrs \\ %{}) do
+ User.password_changeset(user, attrs, hash_password: false)
+ end
+
+ @doc """
+ Updates the user password.
+
+ ## Examples
+
+ iex> update_user_password(user, "valid password", %{password: ...})
+ {:ok, %User{}}
+
+ iex> update_user_password(user, "invalid password", %{password: ...})
+ {:error, %Ecto.Changeset{}}
+
+ """
+ def update_user_password(user, password, attrs) do
+ changeset =
+ user
+ |> User.password_changeset(attrs)
+ |> User.validate_current_password(password)
+
+ Ecto.Multi.new()
+ |> Ecto.Multi.update(:user, changeset)
+ |> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, :all))
+ |> Repo.transaction()
+ |> case do
+ {:ok, %{user: user}} -> {:ok, user}
+ {:error, :user, changeset, _} -> {:error, changeset}
+ end
+ end
+
+ ## Session
+
+ @doc """
+ Generates a session token.
+ """
+ def generate_user_session_token(user) do
+ {token, user_token} = UserToken.build_session_token(user)
+ Repo.insert!(user_token)
+ token
+ end
+
+ @doc """
+ Gets the user with the given signed token.
+ """
+ def get_user_by_session_token(token) do
+ {:ok, query} = UserToken.verify_session_token_query(token)
+ Repo.one(query)
+ end
+
+ @doc """
+ Deletes the signed token with the given context.
+ """
+ def delete_user_session_token(token) do
+ Repo.delete_all(UserToken.by_token_and_context_query(token, "session"))
+ :ok
+ end
+
+ ## Confirmation
+
+ @doc ~S"""
+ Delivers the confirmation email instructions to the given user.
+
+ ## Examples
+
+ iex> deliver_user_confirmation_instructions(user, &url(~p"/users/confirm/#{&1}"))
+ {:ok, %{to: ..., body: ...}}
+
+ iex> deliver_user_confirmation_instructions(confirmed_user, &url(~p"/users/confirm/#{&1}"))
+ {:error, :already_confirmed}
+
+ """
+ def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun)
+ when is_function(confirmation_url_fun, 1) do
+ if user.confirmed_at do
+ {:error, :already_confirmed}
+ else
+ {encoded_token, user_token} = UserToken.build_email_token(user, "confirm")
+ Repo.insert!(user_token)
+ UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
+ end
+ end
+
+ @doc """
+ Confirms a user by the given token.
+
+ If the token matches, the user account is marked as confirmed
+ and the token is deleted.
+ """
+ def confirm_user(token) do
+ with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"),
+ %User{} = user <- Repo.one(query),
+ {:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do
+ {:ok, user}
+ else
+ _ -> :error
+ end
+ end
+
+ defp confirm_user_multi(user) do
+ Ecto.Multi.new()
+ |> Ecto.Multi.update(:user, User.confirm_changeset(user))
+ |> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, ["confirm"]))
+ end
+
+ ## Reset password
+
+ @doc ~S"""
+ Delivers the reset password email to the given user.
+
+ ## Examples
+
+ iex> deliver_user_reset_password_instructions(user, &url(~p"/users/reset_password/#{&1}"))
+ {:ok, %{to: ..., body: ...}}
+
+ """
+ def deliver_user_reset_password_instructions(%User{} = user, reset_password_url_fun)
+ when is_function(reset_password_url_fun, 1) do
+ {encoded_token, user_token} = UserToken.build_email_token(user, "reset_password")
+ Repo.insert!(user_token)
+ UserNotifier.deliver_reset_password_instructions(user, reset_password_url_fun.(encoded_token))
+ end
+
+ @doc """
+ Gets the user by reset password token.
+
+ ## Examples
+
+ iex> get_user_by_reset_password_token("validtoken")
+ %User{}
+
+ iex> get_user_by_reset_password_token("invalidtoken")
+ nil
+
+ """
+ def get_user_by_reset_password_token(token) do
+ with {:ok, query} <- UserToken.verify_email_token_query(token, "reset_password"),
+ %User{} = user <- Repo.one(query) do
+ user
+ else
+ _ -> nil
+ end
+ end
+
+ @doc """
+ Resets the user password.
+
+ ## Examples
+
+ iex> reset_user_password(user, %{password: "new long password", password_confirmation: "new long password"})
+ {:ok, %User{}}
+
+ iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"})
+ {:error, %Ecto.Changeset{}}
+
+ """
+ def reset_user_password(user, attrs) do
+ Ecto.Multi.new()
+ |> Ecto.Multi.update(:user, User.password_changeset(user, attrs))
+ |> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, :all))
+ |> Repo.transaction()
+ |> case do
+ {:ok, %{user: user}} -> {:ok, user}
+ {:error, :user, changeset, _} -> {:error, changeset}
+ end
+ end
+end
diff --git a/uli-community/lib/uli_community/accounts/user.ex b/uli-community/lib/uli_community/accounts/user.ex
new file mode 100644
index 00000000..ab70457f
--- /dev/null
+++ b/uli-community/lib/uli_community/accounts/user.ex
@@ -0,0 +1,162 @@
+defmodule UliCommunity.Accounts.User do
+ use Ecto.Schema
+ import Ecto.Changeset
+
+ schema "users" do
+ field :email, :string
+ field :password, :string, virtual: true, redact: true
+ field :hashed_password, :string, redact: true
+ field :current_password, :string, virtual: true, redact: true
+ field :confirmed_at, :utc_datetime
+ field :role, Ecto.Enum, values: [:user, :admin]
+
+ timestamps(type: :utc_datetime)
+ end
+
+ @doc """
+ A user changeset for registration.
+
+ It is important to validate the length of both email and password.
+ Otherwise databases may truncate the email without warnings, which
+ could lead to unpredictable or insecure behaviour. Long passwords may
+ also be very expensive to hash for certain algorithms.
+
+ ## Options
+
+ * `:hash_password` - Hashes the password so it can be stored securely
+ in the database and ensures the password field is cleared to prevent
+ leaks in the logs. If password hashing is not needed and clearing the
+ password field is not desired (like when using this changeset for
+ validations on a LiveView form), this option can be set to `false`.
+ Defaults to `true`.
+
+ * `:validate_email` - Validates the uniqueness of the email, in case
+ you don't want to validate the uniqueness of the email (like when
+ using this changeset for validations on a LiveView form before
+ submitting the form), this option can be set to `false`.
+ Defaults to `true`.
+ """
+ def registration_changeset(user, attrs, opts \\ []) do
+ user
+ |> cast(attrs, [:email, :password])
+ |> validate_email(opts)
+ |> validate_password(opts)
+ end
+
+ defp validate_email(changeset, opts) do
+ changeset
+ |> validate_required([:email])
+ |> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
+ |> validate_length(:email, max: 160)
+ |> maybe_validate_unique_email(opts)
+ end
+
+ defp validate_password(changeset, opts) do
+ changeset
+ |> validate_required([:password])
+ |> validate_length(:password, min: 12, max: 72)
+ # Examples of additional password validation:
+ # |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character")
+ # |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character")
+ # |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character")
+ |> maybe_hash_password(opts)
+ end
+
+ defp maybe_hash_password(changeset, opts) do
+ hash_password? = Keyword.get(opts, :hash_password, true)
+ password = get_change(changeset, :password)
+
+ if hash_password? && password && changeset.valid? do
+ changeset
+ # If using Bcrypt, then further validate it is at most 72 bytes long
+ |> validate_length(:password, max: 72, count: :bytes)
+ # Hashing could be done with `Ecto.Changeset.prepare_changes/2`, but that
+ # would keep the database transaction open longer and hurt performance.
+ |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
+ |> delete_change(:password)
+ else
+ changeset
+ end
+ end
+
+ defp maybe_validate_unique_email(changeset, opts) do
+ if Keyword.get(opts, :validate_email, true) do
+ changeset
+ |> unsafe_validate_unique(:email, UliCommunity.Repo)
+ |> unique_constraint(:email)
+ else
+ changeset
+ end
+ end
+
+ @doc """
+ A user changeset for changing the email.
+
+ It requires the email to change otherwise an error is added.
+ """
+ def email_changeset(user, attrs, opts \\ []) do
+ user
+ |> cast(attrs, [:email])
+ |> validate_email(opts)
+ |> case do
+ %{changes: %{email: _}} = changeset -> changeset
+ %{} = changeset -> add_error(changeset, :email, "did not change")
+ end
+ end
+
+ @doc """
+ A user changeset for changing the password.
+
+ ## Options
+
+ * `:hash_password` - Hashes the password so it can be stored securely
+ in the database and ensures the password field is cleared to prevent
+ leaks in the logs. If password hashing is not needed and clearing the
+ password field is not desired (like when using this changeset for
+ validations on a LiveView form), this option can be set to `false`.
+ Defaults to `true`.
+ """
+ def password_changeset(user, attrs, opts \\ []) do
+ user
+ |> cast(attrs, [:password])
+ |> validate_confirmation(:password, message: "does not match password")
+ |> validate_password(opts)
+ end
+
+ @doc """
+ Confirms the account by setting `confirmed_at`.
+ """
+ def confirm_changeset(user) do
+ now = DateTime.utc_now() |> DateTime.truncate(:second)
+ change(user, confirmed_at: now)
+ end
+
+ @doc """
+ Verifies the password.
+
+ If there is no user or the user doesn't have a password, we call
+ `Bcrypt.no_user_verify/0` to avoid timing attacks.
+ """
+ def valid_password?(%UliCommunity.Accounts.User{hashed_password: hashed_password}, password)
+ when is_binary(hashed_password) and byte_size(password) > 0 do
+ Bcrypt.verify_pass(password, hashed_password)
+ end
+
+ def valid_password?(_, _) do
+ Bcrypt.no_user_verify()
+ false
+ end
+
+ @doc """
+ Validates the current password otherwise adds an error to the changeset.
+ """
+ def validate_current_password(changeset, password) do
+ changeset = cast(changeset, %{current_password: password}, [:current_password])
+
+ if valid_password?(changeset.data, password) do
+ changeset
+ else
+ add_error(changeset, :current_password, "is not valid")
+ end
+ end
+end
diff --git a/uli-community/lib/uli_community/accounts/user_notifier.ex b/uli-community/lib/uli_community/accounts/user_notifier.ex
new file mode 100644
index 00000000..bd8faa64
--- /dev/null
+++ b/uli-community/lib/uli_community/accounts/user_notifier.ex
@@ -0,0 +1,79 @@
+defmodule UliCommunity.Accounts.UserNotifier do
+ import Swoosh.Email
+
+ alias UliCommunity.Mailer
+
+ # Delivers the email using the application mailer.
+ defp deliver(recipient, subject, body) do
+ email =
+ new()
+ |> to(recipient)
+ |> from({"UliCommunity", "contact@example.com"})
+ |> subject(subject)
+ |> text_body(body)
+
+ with {:ok, _metadata} <- Mailer.deliver(email) do
+ {:ok, email}
+ end
+ end
+
+ @doc """
+ Deliver instructions to confirm account.
+ """
+ def deliver_confirmation_instructions(user, url) do
+ deliver(user.email, "Confirmation instructions", """
+
+ ==============================
+
+ Hi #{user.email},
+
+ You can confirm your account by visiting the URL below:
+
+ #{url}
+
+ If you didn't create an account with us, please ignore this.
+
+ ==============================
+ """)
+ end
+
+ @doc """
+ Deliver instructions to reset a user password.
+ """
+ def deliver_reset_password_instructions(user, url) do
+ deliver(user.email, "Reset password instructions", """
+
+ ==============================
+
+ Hi #{user.email},
+
+ You can reset your password by visiting the URL below:
+
+ #{url}
+
+ If you didn't request this change, please ignore this.
+
+ ==============================
+ """)
+ end
+
+ @doc """
+ Deliver instructions to update a user email.
+ """
+ def deliver_update_email_instructions(user, url) do
+ deliver(user.email, "Update email instructions", """
+
+ ==============================
+
+ Hi #{user.email},
+
+ You can change your email by visiting the URL below:
+
+ #{url}
+
+ If you didn't request this change, please ignore this.
+
+ ==============================
+ """)
+ end
+end
diff --git a/uli-community/lib/uli_community/accounts/user_token.ex b/uli-community/lib/uli_community/accounts/user_token.ex
new file mode 100644
index 00000000..894481e1
--- /dev/null
+++ b/uli-community/lib/uli_community/accounts/user_token.ex
@@ -0,0 +1,179 @@
+defmodule UliCommunity.Accounts.UserToken do
+ use Ecto.Schema
+ import Ecto.Query
+ alias UliCommunity.Accounts.UserToken
+
+ @hash_algorithm :sha256
+ @rand_size 32
+
+ # It is very important to keep the reset password token expiry short,
+ # since someone with access to the email may take over the account.
+ @reset_password_validity_in_days 1
+ @confirm_validity_in_days 7
+ @change_email_validity_in_days 7
+ @session_validity_in_days 60
+
+ schema "users_tokens" do
+ field :token, :binary
+ field :context, :string
+ field :sent_to, :string
+ belongs_to :user, UliCommunity.Accounts.User
+
+ timestamps(type: :utc_datetime, updated_at: false)
+ end
+
+ @doc """
+ Generates a token that will be stored in a signed place,
+ such as session or cookie. As they are signed, those
+ tokens do not need to be hashed.
+
+ The reason why we store session tokens in the database, even
+ though Phoenix already provides a session cookie, is because
+ Phoenix' default session cookies are not persisted, they are
+ simply signed and potentially encrypted. This means they are
+ valid indefinitely, unless you change the signing/encryption
+ salt.
+
+ Therefore, storing them allows individual user
+ sessions to be expired. The token system can also be extended
+ to store additional data, such as the device used for logging in.
+ You could then use this information to display all valid sessions
+ and devices in the UI and allow users to explicitly expire any
+ session they deem invalid.
+ """
+ def build_session_token(user) do
+ token = :crypto.strong_rand_bytes(@rand_size)
+ {token, %UserToken{token: token, context: "session", user_id: user.id}}
+ end
+
+ @doc """
+ Checks if the token is valid and returns its underlying lookup query.
+
+ The query returns the user found by the token, if any.
+
+ The token is valid if it matches the value in the database and it has
+ not expired (after @session_validity_in_days).
+ """
+ def verify_session_token_query(token) do
+ query =
+ from token in by_token_and_context_query(token, "session"),
+ join: user in assoc(token, :user),
+ where: token.inserted_at > ago(@session_validity_in_days, "day"),
+ select: user
+
+ {:ok, query}
+ end
+
+ @doc """
+ Builds a token and its hash to be delivered to the user's email.
+
+ The non-hashed token is sent to the user email while the
+ hashed part is stored in the database. The original token cannot be reconstructed,
+ which means anyone with read-only access to the database cannot directly use
+ the token in the application to gain access. Furthermore, if the user changes
+ their email in the system, the tokens sent to the previous email are no longer
+ valid.
+
+ Users can easily adapt the existing code to provide other types of delivery methods,
+ for example, by phone numbers.
+ """
+ def build_email_token(user, context) do
+ build_hashed_token(user, context, user.email)
+ end
+
+ defp build_hashed_token(user, context, sent_to) do
+ token = :crypto.strong_rand_bytes(@rand_size)
+ hashed_token = :crypto.hash(@hash_algorithm, token)
+
+ {Base.url_encode64(token, padding: false),
+ %UserToken{
+ token: hashed_token,
+ context: context,
+ sent_to: sent_to,
+ user_id: user.id
+ }}
+ end
+
+ @doc """
+ Checks if the token is valid and returns its underlying lookup query.
+
+ The query returns the user found by the token, if any.
+
+ The given token is valid if it matches its hashed counterpart in the
+ database and the user email has not changed. This function also checks
+ if the token is being used within a certain period, depending on the
+ context. The default contexts supported by this function are either
+ "confirm", for account confirmation emails, and "reset_password",
+ for resetting the password. For verifying requests to change the email,
+ see `verify_change_email_token_query/2`.
+ """
+ def verify_email_token_query(token, context) do
+ case Base.url_decode64(token, padding: false) do
+ {:ok, decoded_token} ->
+ hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
+ days = days_for_context(context)
+
+ query =
+ from token in by_token_and_context_query(hashed_token, context),
+ join: user in assoc(token, :user),
+ where: token.inserted_at > ago(^days, "day") and token.sent_to == user.email,
+ select: user
+
+ {:ok, query}
+
+ :error ->
+ :error
+ end
+ end
+
+ defp days_for_context("confirm"), do: @confirm_validity_in_days
+ defp days_for_context("reset_password"), do: @reset_password_validity_in_days
+
+ @doc """
+ Checks if the token is valid and returns its underlying lookup query.
+
+ The query returns the user found by the token, if any.
+
+ This is used to validate requests to change the user
+ email. It is different from `verify_email_token_query/2` precisely because
+ `verify_email_token_query/2` validates the email has not changed, which is
+ the starting point by this function.
+
+ The given token is valid if it matches its hashed counterpart in the
+ database and if it has not expired (after @change_email_validity_in_days).
+ The context must always start with "change:".
+ """
+ def verify_change_email_token_query(token, "change:" <> _ = context) do
+ case Base.url_decode64(token, padding: false) do
+ {:ok, decoded_token} ->
+ hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
+
+ query =
+ from token in by_token_and_context_query(hashed_token, context),
+ where: token.inserted_at > ago(@change_email_validity_in_days, "day")
+
+ {:ok, query}
+
+ :error ->
+ :error
+ end
+ end
+
+ @doc """
+ Returns the token struct for the given token value and context.
+ """
+ def by_token_and_context_query(token, context) do
+ from UserToken, where: [token: ^token, context: ^context]
+ end
+
+ @doc """
+ Gets all tokens for the given user for the given contexts.
+ """
+ def by_user_and_contexts_query(user, :all) do
+ from t in UserToken, where: t.user_id == ^user.id
+ end
+
+ def by_user_and_contexts_query(user, [_ | _] = contexts) do
+ from t in UserToken, where: t.user_id == ^user.id and t.context in ^contexts
+ end
+end
diff --git a/uli-community/lib/uli_community/api.ex b/uli-community/lib/uli_community/api.ex
new file mode 100644
index 00000000..75acfbc2
--- /dev/null
+++ b/uli-community/lib/uli_community/api.ex
@@ -0,0 +1,35 @@
+defmodule UliCommunity.Api do
+ alias UliCommunity.Repo
+ alias UliCommunity.Api.AccessToken
+
+ def add_new_access_token(attrs) do
+ attrs = Map.put_new(attrs, :token_id, Ecto.UUID.generate())
+
+ %AccessToken{}
+ |> AccessToken.changeset(attrs)
+ |> Repo.insert()
+ end
+
+ def get_access_tokens_by_user_id(id) do
+ import Ecto.Query, only: [from: 2]
+
+ query =
+ from token in AccessToken,
+ where: token.created_by_user == ^id,
+ order_by: [desc: token.inserted_at]
+
+ Repo.all(query)
+ end
+
+ def get_access_token(token_id) do
+ Repo.get_by(AccessToken, token_id: token_id)
+ end
+
+ def delete_access_token_by_token_id(token_id) do
+ entry = Repo.get_by(AccessToken, token_id: token_id)
+
+ if entry do
+ Repo.delete(entry)
+ end
+ end
+end
diff --git a/uli-community/lib/uli_community/api/access_token.ex b/uli-community/lib/uli_community/api/access_token.ex
new file mode 100644
index 00000000..63e9bc5d
--- /dev/null
+++ b/uli-community/lib/uli_community/api/access_token.ex
@@ -0,0 +1,21 @@
+defmodule UliCommunity.Api.AccessToken do
+ use Ecto.Schema
+ import Ecto.Changeset
+
+ schema "access_token" do
+ field :token_id, Ecto.UUID
+ field :token_name, :string
+ field :access_level, :string
+ field :expiry, :date
+ field :created_by_user, :integer
+
+ timestamps(type: :utc_datetime)
+ end
+
+ @doc false
+ def changeset(access_token, attrs) do
+ access_token
+ |> cast(attrs, [:token_id, :token_name, :access_level, :expiry, :created_by_user])
+ |> validate_required([:token_id, :token_name, :access_level, :expiry, :created_by_user])
+ end
+end
diff --git a/uli-community/lib/uli_community/api/token.ex b/uli-community/lib/uli_community/api/token.ex
new file mode 100644
index 00000000..b8d3cc1a
--- /dev/null
+++ b/uli-community/lib/uli_community/api/token.ex
@@ -0,0 +1,34 @@
+defmodule UliCommunity.Api.Token do
+ @signing_salt "octosell_api"
+ # token for 2 week
+ @token_age_secs 14 * 86_400
+
+ @doc """
+ Create token for given data
+ """
+ @spec sign(map()) :: binary()
+ def sign(data) do
+ IO.puts("Inside SIGN")
+ token = Phoenix.Token.sign(UliCommunityWeb.Endpoint, @signing_salt, data)
+ IO.inspect(token, label: "Generated TOKEN IS: ")
+ {:ok, token}
+ end
+
+
+ @doc """
+ Verify given token by:
+ - Verify token signature
+ - Verify expiration time
+ """
+ @spec verify(String.t()) :: {:ok, any()} | {:error, :unauthenticated}
+ def verify(token) do
+ case Phoenix.Token.verify(UliCommunityWeb.Endpoint, @signing_salt, token,
+ max_age: @token_age_secs
+ ) do
+ {:ok, data} ->
+
+ {:ok, data}
+ _error -> {:error, :unauthenticated}
+ end
+ end
+end
diff --git a/uli-community/lib/uli_community/application.ex b/uli-community/lib/uli_community/application.ex
new file mode 100644
index 00000000..2b1d1f77
--- /dev/null
+++ b/uli-community/lib/uli_community/application.ex
@@ -0,0 +1,36 @@
+defmodule UliCommunity.Application do
+ # See https://hexdocs.pm/elixir/Application.html
+ # for more information on OTP Applications
+ @moduledoc false
+
+ use Application
+
+ @impl true
+ def start(_type, _args) do
+ children = [
+ UliCommunityWeb.Telemetry,
+ UliCommunity.Repo,
+ {DNSCluster, query: Application.get_env(:uli_community, :dns_cluster_query) || :ignore},
+ {Phoenix.PubSub, name: UliCommunity.PubSub},
+ # Start the Finch HTTP client for sending emails
+ {Finch, name: UliCommunity.Finch},
+ # Start a worker by calling: UliCommunity.Worker.start_link(arg)
+ # {UliCommunity.Worker, arg},
+ # Start to serve requests, typically the last entry
+ UliCommunityWeb.Endpoint
+ ]
+
+ # See https://hexdocs.pm/elixir/Supervisor.html
+ # for other strategies and supported options
+ opts = [strategy: :one_for_one, name: UliCommunity.Supervisor]
+ Supervisor.start_link(children, opts)
+ end
+
+ # Tell Phoenix to update the endpoint configuration
+ # whenever the application is updated.
+ @impl true
+ def config_change(changed, _new, removed) do
+ UliCommunityWeb.Endpoint.config_change(changed, removed)
+ :ok
+ end
+end
diff --git a/uli-community/lib/uli_community/authorization.ex b/uli-community/lib/uli_community/authorization.ex
new file mode 100644
index 00000000..3431bda1
--- /dev/null
+++ b/uli-community/lib/uli_community/authorization.ex
@@ -0,0 +1,23 @@
+defmodule UliCommunity.Authorization do
+ alias ElixirLS.LanguageServer.Plugins.Phoenix
+ alias UliCommunityWeb.Router
+
+ def authorized?(user, path, method, event \\ nil) when is_binary(path) do
+ role = user && user.role
+ uri = URI.parse(path)
+ method = String.upcase(method || "GET")
+ info = Router.route_info(method, uri.path, uri.host)
+ route = info.route
+ action = get_action(info)
+
+ can?(role, route, "#{event || action}")
+ end
+
+ defp can?(_role, "/", _action), do: true
+ defp can?(:user, "/testadmin", _action), do: false
+ defp can?(_role, _route, _action), do: true
+
+ defp get_action(%{phoenix_live_view: plv}), do: elem(plv, 1)
+ defp get_action(%{plug_opts: action}), do: action
+
+end
diff --git a/uli-community/lib/uli_community/mailer.ex b/uli-community/lib/uli_community/mailer.ex
new file mode 100644
index 00000000..bb0770e8
--- /dev/null
+++ b/uli-community/lib/uli_community/mailer.ex
@@ -0,0 +1,3 @@
+defmodule UliCommunity.Mailer do
+ use Swoosh.Mailer, otp_app: :uli_community
+end
diff --git a/uli-community/lib/uli_community/repo.ex b/uli-community/lib/uli_community/repo.ex
new file mode 100644
index 00000000..3f90d48a
--- /dev/null
+++ b/uli-community/lib/uli_community/repo.ex
@@ -0,0 +1,5 @@
+defmodule UliCommunity.Repo do
+ use Ecto.Repo,
+ otp_app: :uli_community,
+ adapter: Ecto.Adapters.Postgres
+end
diff --git a/uli-community/lib/uli_community_web.ex b/uli-community/lib/uli_community_web.ex
new file mode 100644
index 00000000..8e63bb61
--- /dev/null
+++ b/uli-community/lib/uli_community_web.ex
@@ -0,0 +1,113 @@
+defmodule UliCommunityWeb do
+ @moduledoc """
+ The entrypoint for defining your web interface, such
+ as controllers, components, channels, and so on.
+
+ This can be used in your application as:
+
+ use UliCommunityWeb, :controller
+ use UliCommunityWeb, :html
+
+ The definitions below will be executed for every controller,
+ component, etc, so keep them short and clean, focused
+ on imports, uses and aliases.
+
+ Do NOT define functions inside the quoted expressions
+ below. Instead, define additional modules and import
+ those modules here.
+ """
+
+ def static_paths, do: ~w(assets fonts images favicon.ico robots.txt)
+
+ def router do
+ quote do
+ use Phoenix.Router, helpers: false
+
+ # Import common connection and controller functions to use in pipelines
+ import Plug.Conn
+ import Phoenix.Controller
+ import Phoenix.LiveView.Router
+ end
+ end
+
+ def channel do
+ quote do
+ use Phoenix.Channel
+ end
+ end
+
+ def controller do
+ quote do
+ use Phoenix.Controller,
+ formats: [:html, :json],
+ layouts: [html: UliCommunityWeb.Layouts]
+
+ import Plug.Conn
+ import UliCommunityWeb.Gettext
+
+ unquote(verified_routes())
+ end
+ end
+
+ def live_view do
+ quote do
+ use Phoenix.LiveView,
+ layout: {UliCommunityWeb.Layouts, :app}
+
+ unquote(html_helpers())
+ end
+ end
+
+ def live_component do
+ quote do
+ use Phoenix.LiveComponent
+
+ unquote(html_helpers())
+ end
+ end
+
+ def html do
+ quote do
+ use Phoenix.Component
+
+ # Import convenience functions from controllers
+ import Phoenix.Controller,
+ only: [get_csrf_token: 0, view_module: 1, view_template: 1]
+
+ # Include general helpers for rendering HTML
+ unquote(html_helpers())
+ end
+ end
+
+ defp html_helpers do
+ quote do
+ # HTML escaping functionality
+ import Phoenix.HTML
+ # Core UI components and translation
+ import UliCommunityWeb.CoreComponents
+ import UliCommunityWeb.Gettext
+
+ # Shortcut for generating JS commands
+ alias Phoenix.LiveView.JS
+
+ # Routes generation with the ~p sigil
+ unquote(verified_routes())
+ end
+ end
+
+ def verified_routes do
+ quote do
+ use Phoenix.VerifiedRoutes,
+ endpoint: UliCommunityWeb.Endpoint,
+ router: UliCommunityWeb.Router,
+ statics: UliCommunityWeb.static_paths()
+ end
+ end
+
+ @doc """
+ When used, dispatch to the appropriate controller/live_view/etc.
+ """
+ defmacro __using__(which) when is_atom(which) do
+ apply(__MODULE__, which, [])
+ end
+end
diff --git a/uli-community/lib/uli_community_web/components/core_components.ex b/uli-community/lib/uli_community_web/components/core_components.ex
new file mode 100644
index 00000000..08bfd1bc
--- /dev/null
+++ b/uli-community/lib/uli_community_web/components/core_components.ex
@@ -0,0 +1,676 @@
+defmodule UliCommunityWeb.CoreComponents do
+ @moduledoc """
+ Provides core UI components.
+
+ At first glance, this module may seem daunting, but its goal is to provide
+ core building blocks for your application, such as modals, tables, and
+ forms. The components consist mostly of markup and are well-documented
+ with doc strings and declarative assigns. You may customize and style
+ them in any way you want, based on your application growth and needs.
+
+ The default components use Tailwind CSS, a utility-first CSS framework.
+ See the [Tailwind CSS documentation](https://tailwindcss.com) to learn
+ how to customize them or feel free to swap in another framework altogether.
+
+ Icons are provided by [heroicons](https://heroicons.com). See `icon/1` for usage.
+ """
+ use Phoenix.Component
+
+ alias Phoenix.LiveView.JS
+ import UliCommunityWeb.Gettext
+
+ @doc """
+ Renders a modal.
+
+ ## Examples
+
+ <.modal id="confirm-modal">
+ This is a modal.
+
+
+ JS commands may be passed to the `:on_cancel` to configure
+ the closing/cancel event, for example:
+
+ <.modal id="confirm" on_cancel={JS.navigate(~p"/posts")}>
+ This is another modal.
+
+
+ """
+ attr :id, :string, required: true
+ attr :show, :boolean, default: false
+ attr :on_cancel, JS, default: %JS{}
+ slot :inner_block, required: true
+
+ def modal(assigns) do
+ ~H"""
+
+ """
+ end
+
+ @doc """
+ Shows the flash group with standard titles and content.
+
+ ## Examples
+
+ <.flash_group flash={@flash} />
+ """
+ attr :flash, :map, required: true, doc: "the map of flash messages"
+ attr :id, :string, default: "flash-group", doc: "the optional id of flash container"
+
+ def flash_group(assigns) do
+ ~H"""
+
+ <.flash kind={:info} title={gettext("Success!")} flash={@flash} />
+ <.flash kind={:error} title={gettext("Error!")} flash={@flash} />
+ <.flash
+ id="client-error"
+ kind={:error}
+ title={gettext("We can't find the internet")}
+ phx-disconnected={show(".phx-client-error #client-error")}
+ phx-connected={hide("#client-error")}
+ hidden
+ >
+ <%= gettext("Attempting to reconnect") %>
+ <.icon name="hero-arrow-path" class="ml-1 h-3 w-3 animate-spin" />
+
+
+ <.flash
+ id="server-error"
+ kind={:error}
+ title={gettext("Something went wrong!")}
+ phx-disconnected={show(".phx-server-error #server-error")}
+ phx-connected={hide("#server-error")}
+ hidden
+ >
+ <%= gettext("Hang in there while we get back on track") %>
+ <.icon name="hero-arrow-path" class="ml-1 h-3 w-3 animate-spin" />
+
+
+ """
+ end
+
+ @doc """
+ Renders a simple form.
+
+ ## Examples
+
+ <.simple_form for={@form} phx-change="validate" phx-submit="save">
+ <.input field={@form[:email]} label="Email"/>
+ <.input field={@form[:username]} label="Username" />
+ <:actions>
+ <.button>Save
+
+
+ """
+ attr :for, :any, required: true, doc: "the data structure for the form"
+ attr :as, :any, default: nil, doc: "the server side parameter to collect all input under"
+
+ attr :rest, :global,
+ include: ~w(autocomplete name rel action enctype method novalidate target multipart),
+ doc: "the arbitrary HTML attributes to apply to the form tag"
+
+ slot :inner_block, required: true
+ slot :actions, doc: "the slot for form actions, such as a submit button"
+
+ def simple_form(assigns) do
+ ~H"""
+ <.form :let={f} for={@for} as={@as} {@rest}>
+
+ <%= render_slot(@inner_block, f) %>
+
+ <%= render_slot(action, f) %>
+
+
+
+ """
+ end
+
+ @doc """
+ Renders a button.
+
+ ## Examples
+
+ <.button>Send!
+ <.button phx-click="go" class="ml-2">Send!
+ """
+ attr :type, :string, default: nil
+ attr :class, :string, default: nil
+ attr :rest, :global, include: ~w(disabled form name value)
+
+ slot :inner_block, required: true
+
+ def button(assigns) do
+ ~H"""
+
+ """
+ end
+
+ @doc """
+ Renders an input with label and error messages.
+
+ A `Phoenix.HTML.FormField` may be passed as argument,
+ which is used to retrieve the input name, id, and values.
+ Otherwise all attributes may be passed explicitly.
+
+ ## Types
+
+ This function accepts all HTML input types, considering that:
+
+ * You may also set `type="select"` to render a `