Skip to content

Commit

Permalink
feat/Modal Terms and Conditions Dialog
Browse files Browse the repository at this point in the history
  • Loading branch information
maxesse committed Aug 20, 2024
1 parent 45479d4 commit a51e319
Show file tree
Hide file tree
Showing 31 changed files with 9,066 additions and 13,188 deletions.
5 changes: 5 additions & 0 deletions api/models/schema/userSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,12 @@ const userSchema = mongoose.Schema(
type: Date,
expires: 604800, // 7 days in seconds
},
termsAccepted: {
type: Boolean,
default: false,
},
},

{ timestamps: true },
);

Expand Down
29 changes: 29 additions & 0 deletions api/server/controllers/UserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const {
deleteMessages,
deleteUserById,
} = require('~/models');
const User = require('~/models/User'); // Add this line
const { updateUserPluginAuth, deleteUserPluginAuth } = require('~/server/services/PluginService');
const { updateUserPluginsService, deleteUserKey } = require('~/server/services/UserService');
const { verifyEmail, resendVerificationEmail } = require('~/server/services/AuthService');
Expand All @@ -20,6 +21,32 @@ const getUserController = async (req, res) => {
res.status(200).send(req.user);
};

const getTermsStatusController = async (req, res) => {
try {
const user = await User.findById(req.user.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ termsAccepted: !!user.termsAccepted });
} catch (error) {
console.error('Error fetching terms acceptance status:', error);
res.status(500).json({ message: 'Error fetching terms acceptance status' });
}
};

const acceptTermsController = async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.user.id, { termsAccepted: true }, { new: true });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ message: 'Terms accepted successfully' });
} catch (error) {
console.error('Error accepting terms:', error);
res.status(500).json({ message: 'Error accepting terms' });
}
};

const deleteUserFiles = async (req) => {
try {
const userFiles = await getFiles({ user: req.user.id });
Expand Down Expand Up @@ -135,6 +162,8 @@ const resendVerificationController = async (req, res) => {

module.exports = {
getUserController,
getTermsStatusController,
acceptTermsController,
deleteUserController,
verifyEmailController,
updateUserPluginsController,
Expand Down
4 changes: 4 additions & 0 deletions api/server/routes/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ const {
verifyEmailController,
updateUserPluginsController,
resendVerificationController,
getTermsStatusController,
acceptTermsController,
} = require('~/server/controllers/UserController');

const router = express.Router();

router.get('/', requireJwtAuth, getUserController);
router.get('/terms', requireJwtAuth, getTermsStatusController);
router.post('/terms/accept', requireJwtAuth, acceptTermsController);
router.post('/plugins', requireJwtAuth, updateUserPluginsController);
router.delete('/delete', requireJwtAuth, canDeleteAccount, deleteUserController);
router.post('/verify', verifyEmailController);
Expand Down
100 changes: 100 additions & 0 deletions client/src/components/ui/TermsAndConditionsModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { useLocalize } from '~/hooks';
import { Dialog } from '~/components/ui';
import DialogTemplate from '~/components/ui/DialogTemplate';
import { useAuthContext } from '~/hooks';
import Markdown from '~/components/Chat/Messages/Content/Markdown';

const TermsAndConditionsModal = ({
open,
onOpenChange,
onAccept,
onDecline,
title,
modalContent,
}: {
open: boolean;
onOpenChange: (isOpen: boolean) => void;
onAccept: () => void;
onDecline: () => void;
title?: string;
contentUrl?: string;
modalContent?: string;
}) => {
const localize = useLocalize();
const { token } = useAuthContext();

const handleAccept = async () => {
try {
const response = await fetch('/api/user/terms/accept', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
credentials: 'include',
});

if (response.ok) {
onAccept();
onOpenChange(false);
} else {
const errorData = await response.json();
console.error('Failed to accept terms:', errorData.message);
}
} catch (error) {
console.error('Error accepting terms:', error);
}
};

const handleDecline = () => {
onDecline();
onOpenChange(false);
};

const handleOpenChange = (isOpen: boolean) => {
if (open && !isOpen) {
return;
}
onOpenChange(isOpen);
};

return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTemplate
title={title ?? localize('com_ui_terms_and_conditions')}
className="w-11/12 max-w-3xl sm:w-3/4 md:w-1/2 lg:w-2/5"
showCloseButton={false}
showCancelButton={false}
main={
<div className="max-h-[60vh] overflow-y-auto p-4">
<div className="prose dark:prose-invert w-full max-w-none !text-black dark:!text-white">
{modalContent ? (
<Markdown content={modalContent} isLatestMessage={false} />
) : (
<p>{localize('com_ui_no_terms_content')}</p>
)}
</div>
</div>
}
buttons={
<>
<button
onClick={handleDecline}
className="inline-flex h-10 items-center justify-center rounded-lg border-none bg-gray-500 px-4 py-2 text-sm text-white hover:bg-gray-600 dark:hover:bg-gray-600"
>
{localize('com_ui_decline')}
</button>
<button
onClick={handleAccept}
className="inline-flex h-10 items-center justify-center rounded-lg border-none bg-green-500 px-4 py-2 text-sm text-white hover:bg-green-600 dark:hover:bg-green-600"
>
{localize('com_ui_accept')}
</button>
</>
}
/>
</Dialog>
);
};

export default TermsAndConditionsModal;
4 changes: 4 additions & 0 deletions client/src/localization/languages/Ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,10 @@ export default {
com_ui_terms_of_service: 'شروط الخدمة',
com_ui_min_tags: 'لا يمكن إزالة المزيد من القيم، الحد الأدنى المطلوب هو {0}.',
com_ui_max_tags: 'الحد الأقصى المسموح به هو {0}، باستخدام أحدث القيم.',
com_ui_accept: 'أوافق',
com_ui_decline: 'لا أوافق',
com_ui_terms_and_conditions: 'شروط الخدمة',
com_ui_no_terms_content: 'لا يوجد محتوى لشروط الخدمة',
com_auth_back_to_login: 'العودة إلى تسجيل الدخول',
com_endpoint_message: 'رسالة',
com_endpoint_message_not_appendable: 'عدّل رسالتك أو أعد إنشاءها.',
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Br.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ export default {
com_ui_bookmarks_update_error: 'Houve um erro ao atualizar o favorito',
com_ui_bookmarks_delete_error: 'Houve um erro ao excluir o favorito',
com_ui_bookmarks_add_to_conversation: 'Adicionar à conversa atual',
com_ui_accept: 'Eu aceito',
com_ui_decline: 'Eu não aceito',
com_ui_terms_and_conditions: 'Termos e Condições',
com_ui_no_terms_content: 'Nenhum conteúdo de termos e condições para exibir',
com_auth_error_login:
'Não foi possível fazer login com as informações fornecidas. Por favor, verifique suas credenciais e tente novamente.',
com_auth_error_login_rl:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/De.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,10 @@ export default {
com_ui_bookmarks_delete_error: 'Beim Löschen des Lesezeichens ist ein Fehler aufgetreten',
com_ui_bookmarks_add_to_conversation: 'Zur aktuellen Konversation hinzufügen',
com_ui_bookmarks_filter: 'Lesezeichen filtern...',
com_ui_accept: 'Ich akzeptiere',
com_ui_decline: 'Ich akzeptiere nicht',
com_ui_terms_and_conditions: 'Allgemeine Geschäftsbedingungen',
com_ui_no_terms_content: 'Keine Inhalte der Allgemeinen Geschäftsbedingungen zum Anzeigen',
com_auth_error_login:
'Anmeldung mit den angegebenen Informationen nicht möglich. Bitte überprüfe deine Anmeldedaten und versuche es erneut.',
com_auth_error_login_rl:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Eng.ts
Original file line number Diff line number Diff line change
Expand Up @@ -749,4 +749,8 @@ export default {
com_nav_lang_indonesia: 'Indonesia',
com_nav_lang_hebrew: 'עברית',
com_nav_lang_finnish: 'Suomi',
com_ui_accept: 'I accept',
com_ui_decline: 'I do not accept',
com_ui_terms_and_conditions: 'Terms and Conditions',
com_ui_no_terms_content: 'No terms and conditions content to display',
};
4 changes: 4 additions & 0 deletions client/src/localization/languages/Es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,10 @@ export default {
com_ui_bookmarks_update_error: 'Hubo un error al actualizar el marcador',
com_ui_bookmarks_delete_error: 'Hubo un error al eliminar el marcador',
com_ui_bookmarks_add_to_conversation: 'Agregar a la conversación actual',
com_ui_accept: 'Acepto',
com_ui_decline: 'No acepto',
com_ui_terms_and_conditions: 'Términos y Condiciones',
com_ui_no_terms_content: 'No hay contenido de términos y condiciones para mostrar',
com_auth_error_login:
'No se puede iniciar sesión con la información proporcionada. Verifique sus credenciales y vuelva a intentarlo.',
com_auth_error_login_rl:
Expand Down
10 changes: 7 additions & 3 deletions client/src/localization/languages/Fi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,7 @@ export default {
com_ui_bookmarks: 'Kirjanmerkit',
com_ui_bookmarks_rebuild: 'Uudelleenkokoa',
com_ui_bookmarks_new: 'Uusi kirjanmerkki',
com_ui_bookmark_delete_confirm:
'Oletko varma, että haluat poistaa tämän kirjanmerkin?',
com_ui_bookmark_delete_confirm: 'Oletko varma, että haluat poistaa tämän kirjanmerkin?',
com_ui_bookmarks_title: 'Otsikko',
com_ui_bookmarks_count: 'Määrä',
com_ui_bookmarks_description: 'Kuvaus',
Expand All @@ -307,6 +306,10 @@ export default {
com_ui_bookmarks_update_error: 'Virhe kirjanmerkin päivittämisessä',
com_ui_bookmarks_delete_error: 'Virhe kirjanmerkin poistamisessa',
com_ui_bookmarks_add_to_conversation: 'Lisää nykyiseen keskusteluun',
com_ui_accept: 'Hyväksyn',
com_ui_decline: 'En hyväksy',
com_ui_terms_and_conditions: 'Käyttöehdot',
com_ui_no_terms_content: 'Ei käyttöehtoja näytettäväksi',
com_auth_error_login:
'Kirjautuminen annetuilla tiedoilla ei onnistunut. Tarkista kirjautumistiedot, ja yritä uudestaan.',
com_auth_error_login_rl:
Expand Down Expand Up @@ -402,7 +405,8 @@ export default {
com_endpoint_token_count: 'Token-määrä',
com_endpoint_output: 'Tulos',
com_endpoint_context_tokens: 'Konteksti-tokenien maksimimäärä',
com_endpoint_context_info: 'Kontekstia varten käytettävien tokeneiden maksimimäärä. Käytä tätä pyyntökohtaisten token-määrien hallinnointiin. Jos tätä ei määritetä, käytössä ovat järjestelmän oletusarvot perustuen tiedossa olevien mallien konteksti-ikkunoiden kokoon. Korkeamman arvon asettaminen voi aiheuttaa virheitä tai korkeamman token-hinnan.',
com_endpoint_context_info:
'Kontekstia varten käytettävien tokeneiden maksimimäärä. Käytä tätä pyyntökohtaisten token-määrien hallinnointiin. Jos tätä ei määritetä, käytössä ovat järjestelmän oletusarvot perustuen tiedossa olevien mallien konteksti-ikkunoiden kokoon. Korkeamman arvon asettaminen voi aiheuttaa virheitä tai korkeamman token-hinnan.',
com_endpoint_google_temp:
'Korkeampi arvo = satunnaisempi; matalampi arvo = keskittyneempi ja deterministisempi. Suosittelemme, että muokkaat tätä tai Top P:tä, mutta ei molempia.',
com_endpoint_google_topp:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ export default {
com_ui_bookmarks_update_error: 'Une erreur est survenue lors de la mise à jour du signet',
com_ui_bookmarks_delete_error: 'Une erreur est survenue lors de la suppression du signet',
com_ui_bookmarks_add_to_conversation: 'Ajouter à la conversation en cours',
com_ui_accept: 'J\'accepte',
com_ui_decline: 'Je n\'accepte pas',
com_ui_terms_and_conditions: 'Conditions d\'utilisation',
com_ui_no_terms_content: 'Aucun contenu de conditions d\'utilisation à afficher',
com_auth_error_login:
'Impossible de se connecter avec les informations fournies. Veuillez vérifier vos identifiants et réessayer.',
com_auth_error_login_rl:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/He.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ export default {
com_ui_bookmarks_update_error: 'אירעה שגיאה בעת עדכון הסימניה',
com_ui_bookmarks_delete_error: 'אירעה שגיאה בעת מחיקת הסימניה',
com_ui_bookmarks_add_to_conversation: 'הוסף לשיחה הנוכחית',
com_ui_accept: 'אני מקבל',
com_ui_decline: 'אני לא מקבל',
com_ui_terms_and_conditions: 'תנאים והגבלות',
com_ui_no_terms_content: 'אין תוכן תנאים והגבלות להצגה',
com_auth_error_login: 'לא ניתן להתחבר עם המידע שסופק. אנא בדוק את האישורים שלך ונסה שוב.',
com_auth_error_login_rl: 'יותר מדי ניסיונות כניסה בזמן קצר. בבקשה נסה שוב מאוחר יותר.',
com_auth_error_login_ban: 'החשבון שלך נחסם באופן זמני עקב הפרות של השירות שלנו.',
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ export default {
com_ui_bookmarks_update_error: 'Terjadi kesalahan saat memperbarui penanda',
com_ui_bookmarks_delete_error: 'Terjadi kesalahan saat menghapus penanda',
com_ui_bookmarks_add_to_conversation: 'Tambahkan ke percakapan saat ini',
com_ui_accept: 'Saya menerima',
com_ui_decline: 'Saya tidak menerima',
com_ui_terms_and_conditions: 'Syarat dan Ketentuan',
com_ui_no_terms_content: 'Tidak ada konten syarat dan ketentuan untuk ditampilkan',
com_auth_error_login:
'Tidak dapat masuk dengan informasi yang diberikan. Silakan periksa kredensial Anda dan coba lagi.',
com_auth_error_login_rl:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/It.ts
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,10 @@ export default {
com_user_message: 'Mostra nome utente nei messaggi',
com_ui_fork: 'Duplica',
com_ui_mention: 'Menziona un endpoint, assistente o preset per passare rapidamente ad esso',
com_ui_accept: 'Accetto',
com_ui_decline: 'Non accetto',
com_ui_terms_and_conditions: 'Termini d\'uso',
com_ui_no_terms_content: 'Nessun contenuto dei termini d\'uso da visualizzare',
com_endpoint_context_tokens: 'Token di Contesto Massimi',
com_endpoint_context_info:
'Il numero massimo di token che possono essere utilizzati per il contesto. Usalo per controllare quanti token vengono inviati per richiesta. Se non specificato, verranno utilizzate le impostazioni di sistema predefinite in base alle dimensioni del contesto dei modelli noti. Impostare valori più alti potrebbe causare errori e/o costi di token più elevati.',
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Jp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ export default {
com_ui_bookmarks_update_error: 'ブックマークの更新中にエラーが発生しました',
com_ui_bookmarks_delete_error: 'ブックマークの削除中にエラーが発生しました',
com_ui_bookmarks_add_to_conversation: '現在の会話に追加',
com_ui_accept: '同意します',
com_ui_decline: '同意しません',
com_ui_terms_and_conditions: '利用規約',
com_ui_no_terms_content: '利用規約の内容がありません',
com_auth_error_login:
'入力された情報ではログインできませんでした。認証情報を確認した上で再度お試しください。',
com_auth_error_login_rl:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ export default {
com_ui_bookmarks_update_error: '북마크 업데이트 중 오류가 발생했습니다',
com_ui_bookmarks_delete_error: '북마크 삭제 중 오류가 발생했습니다',
com_ui_bookmarks_add_to_conversation: '현재 대화에 추가',
com_ui_accept: '동의합니다',
com_ui_decline: '동의하지 않습니다',
com_ui_terms_and_conditions: '이용 약관',
com_ui_no_terms_content: '이용 약관 내용이 없습니다',
com_auth_error_login: '제공된 정보로 로그인할 수 없습니다. 자격 증명을 확인하고 다시 시도하세요.',
com_auth_no_account: '계정이 없으신가요?',
com_auth_sign_up: '가입하기',
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Nl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ export default {
com_ui_bookmarks_update_error: 'Er is een fout opgetreden bij het bijwerken van de bladwijzer',
com_ui_bookmarks_delete_error: 'Er is een fout opgetreden bij het verwijderen van de bladwijzer',
com_ui_bookmarks_add_to_conversation: 'Toevoegen aan huidig gesprek',
com_ui_accept: 'Ik accepteer',
com_ui_decline: 'Ik accepteer niet',
com_ui_terms_and_conditions: 'Gebruiksvoorwaarden',
com_ui_no_terms_content: 'Geen gebruiksvoorwaarden-inhoud om weer te geven',
com_auth_error_login:
'Kan niet inloggen met de verstrekte informatie. Controleer uw referenties en probeer het opnieuw.',
com_auth_error_login_rl: 'Te veel inlogpogingen in een korte tijd. Probeer het later nog eens.',
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,10 @@ export default {
com_ui_import_conversation_info: 'Importuj konwersacje z pliku JSON',
com_ui_import_conversation_success: 'Konwersacje zostały pomyślnie zaimportowane',
com_ui_import_conversation_error: 'Wystąpił błąd podczas importowania konwersacji',
com_ui_accept: 'Akceptuję',
com_ui_decline: 'Nie akceptuję',
com_ui_terms_and_conditions: 'Warunki użytkowania',
com_ui_no_terms_content: 'Brak treści warunków użytkowania do wyświetlenia',
};

export const comparisons = {
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ export default {
com_ui_bookmarks_update_error: 'Произошла ошибка при обновлении закладки',
com_ui_bookmarks_delete_error: 'Произошла ошибка при удалении закладки',
com_ui_bookmarks_add_to_conversation: 'Добавить в текущий разговор',
com_ui_accept: 'Принимаю',
com_ui_decline: 'Не принимаю',
com_ui_terms_and_conditions: 'Условия использования',
com_ui_no_terms_content: 'Нет содержания условий использования для отображения',
com_auth_error_login:
'Не удалось войти с предоставленной информацией. Пожалуйста, проверьте ваши учетные данные и попробуйте снова.',
com_auth_error_login_rl:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Sv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ export default {
com_ui_bookmarks_update_error: 'Ett fel uppstod vid uppdateringen av bokmärket',
com_ui_bookmarks_delete_error: 'Ett fel uppstod vid raderingen av bokmärket',
com_ui_bookmarks_add_to_conversation: 'Lägg till i nuvarande konversation',
com_ui_accept: 'Jag accepterar',
com_ui_decline: 'Jag accepterar inte',
com_ui_terms_and_conditions: 'Villkor för användning',
com_ui_no_terms_content: 'Ingen innehåll för villkor för användning att visa',
com_auth_error_login:
'Kunde inte logga in med den angivna informationen. Kontrollera dina uppgifter och försök igen.',
com_auth_error_login_rl:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Tr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,10 @@ export default {
com_ui_bookmarks_update_error: 'Yer imi güncellenirken bir hata oluştu',
com_ui_bookmarks_delete_error: 'Yer imi silinirken bir hata oluştu',
com_ui_bookmarks_add_to_conversation: 'Mevcut sohbete ekle',
com_ui_accept: 'Kabul ediyorum',
com_ui_decline: 'Kabul etmiyorum',
com_ui_terms_and_conditions: 'Şartlar ve koşullar',
com_ui_no_terms_content: 'Şartlar ve koşullar için içerik bulunmuyor',
com_auth_error_login:
'Sağlanan bilgilerle giriş yapılamıyor. Lütfen kimlik bilgilerinizi kontrol edin ve tekrar deneyin.',
com_auth_error_login_rl:
Expand Down
4 changes: 4 additions & 0 deletions client/src/localization/languages/Vi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ export default {
com_ui_bookmarks_update_error: 'Có lỗi xảy ra khi cập nhật dấu trang',
com_ui_bookmarks_delete_error: 'Có lỗi xảy ra khi x��a dấu trang',
com_ui_bookmarks_add_to_conversation: 'Thêm vào cuộc hội thoại hiện tại',
com_ui_accept: 'Tôi chấp nhận',
com_ui_decline: 'Tôi không chấp nhận',
com_ui_terms_and_conditions: 'Điều khoản và điều kiện',
com_ui_no_terms_content: 'Không có nội dung điều khoản và điều kiện để hiển thị',
com_auth_error_login:
'Không thể đăng nhập với thông tin được cung cấp. Vui lòng kiểm tra thông tin đăng nhập và thử lại.',
com_auth_error_login_rl:
Expand Down
Loading

0 comments on commit a51e319

Please sign in to comment.