Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

task(api): adiciona a url da photo do usuário no bando de dados #86

Merged
merged 19 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
config: copy-env setup-env config-mock entrypoint-chmod
copy-env:
cp ./api/.env.example ./api/.env
cp ./web/.env.example ./web/.env.local

setup-env:
bash scripts/env.sh
Expand Down
4 changes: 4 additions & 0 deletions api/users/backends/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def get_user_data(cls, access_token: str) -> dict | None:
response._content = b'''{
"given_name": "given_name",
"family_name": "family_name",
"picture_url": "https://photo.aqui.com",
"email": "[email protected]"
}'''
response.status_code = status.HTTP_200_OK
Expand All @@ -48,6 +49,9 @@ def do_auth(user_data: dict) -> User | None:

if user_data.get('family_name'):
user.last_name = user_data['family_name']

if user_data.get('picture_url'):
user.picture_url = user_data['picture_url']

if created:
user.save()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 4.2.5 on 2023-11-15 22:01

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('users', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='user',
name='picture_url',
field=models.URLField(default=''),
),
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(default='', max_length=64),
),
migrations.AlterField(
model_name='user',
name='last_name',
field=models.CharField(default='', max_length=128),
),
]
5 changes: 3 additions & 2 deletions api/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@

class User(AbstractUser):
uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=128)
first_name = models.CharField(default='', max_length=64)
last_name = models.CharField(default='', max_length=128)
email = models.EmailField(blank=False, unique=True)
picture_url = models.URLField(default='')
is_active = models.BooleanField(default=True)

REQUIRED_FIELDS = ["email"]
2 changes: 2 additions & 0 deletions api/users/simplejwt/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ def validate(self, attrs: dict[str, any]) -> dict[str, any]:
user = jwt_authentication.get_user(validated_token)

data["first_name"] = str(user.first_name)
data["last_name"] = str(user.last_name)
data["picture_url"] = str(user.picture_url)
data["email"] = str(user.email)

return data
5 changes: 5 additions & 0 deletions api/users/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ def test_google_register_with_valid_token(self) -> None:

created_user = users.get(email='[email protected]')
self.assertEqual(created_user.first_name, 'given_name')
self.assertEqual(created_user.last_name, 'family_name')
self.assertEqual(created_user.picture_url, 'https://photo.aqui.com')
self.assertEqual(created_user.email, '[email protected]')
self.assertEqual(response.status_code, status.HTTP_200_OK)

Expand Down Expand Up @@ -181,6 +183,7 @@ def setUp(self) -> None:
self.user, _ = User.objects.get_or_create(
first_name="test",
last_name="banana",
picture_url="https://photo.aqui.com",
email="[email protected]",
)
self.user.save()
Expand Down Expand Up @@ -238,6 +241,8 @@ def test_user_login_with_valid_token(self) -> None:

self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['first_name'], self.user.first_name)
self.assertEqual(response.data['last_name'], self.user.last_name)
self.assertEqual(response.data['picture_url'], self.user.picture_url)
self.assertEqual(response.data['email'], self.user.email)

def test_user_login_access_token(self) -> None:
Expand Down
2 changes: 2 additions & 0 deletions api/users/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ def post(self, request: Request, *args, **kwargs) -> Response:
'access': str(refresh.access_token),
'refresh': str(refresh),
'first_name': user.first_name,
'last_name': user.last_name,
'picture_url': user.picture_url,
'email': user.email,
}

Expand Down
8 changes: 8 additions & 0 deletions web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Django API URL
NEXT_PUBLIC_API_URL='http://localhost:8000'

# Google OAuth URL
NEXT_PUBLIC_GOOGLE_OAUTH_URL='https://accounts.google.com/o/oauth2/v2/auth'

# Google OAuth Client ID
NEXT_PUBLIC_GOOGLE_OAUTH_CLIENT_ID='your_client_id'
14 changes: 12 additions & 2 deletions web/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
{
"extends": "next/core-web-vitals"
}
"extends": "next/core-web-vitals",
"rules": {
"semi": [
"error",
"always"
],
"quotes": [
"error",
"single"
]
}
}
17 changes: 17 additions & 0 deletions web/app/components/Button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { HTMLProps } from 'react';

interface ButtonPropsType extends HTMLProps<HTMLButtonElement> {
children: React.ReactNode;
}

export default function Button({ children, ...props }: ButtonPropsType) {
return (
<button
{...props}
className={`flex justify-center items-center gap-3 font-medium rounded-xl shadow py-3 px-5 hover:shadow-md transition-all duration-300 ${props.className || ''}`}
type='submit'
>
{children}
</button>
);
}
64 changes: 64 additions & 0 deletions web/app/components/SignInSection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import useUser from '../hooks/useUser';

import signInWithGoogle from '../utils/signInWithGoogle';
import registerWithGoogle from '../utils/api/registerWithGoogle';
import retrieveAccessToken from '../utils/retrieveAccessToken';

import googleLogoImage from '../../public/google.svg';

import Image from 'next/image';
import Button from './Button';
import toast from 'react-hot-toast';

interface UserData {
access: string;
first_name: string;
email: string;

}

export default function SignInSection() {
const router = useRouter();
const { user, setUser } = useUser();
const [accessToken, setAccessToken] = useState<string>();

useEffect(() => {
setAccessToken(retrieveAccessToken());
}, [setAccessToken]);

useEffect(() => {
if (accessToken) {
registerWithGoogle(accessToken).then(response => {
const userData: UserData = response.data;
setUser({
is_anonymous: false,
access: userData.access,
first_name: userData.first_name,
email: userData.email,
});
router.push('/schedules/home');
}).catch(error => {
toast.error('Algo deu errado: ' + error.response.data.errors);
});
}
}, [accessToken, router, setUser]);

return (
<Button
className='text-sm hover:bg-slate-100 bg-white text-black'
onClick={() => {
if (!user.is_anonymous) router.push('/schedules/home');
else signInWithGoogle(router);
}}
>
<Image
src={googleLogoImage} alt='Logo do Google'
/>
Continuar com o Google
</Button>
);
}
35 changes: 35 additions & 0 deletions web/app/contexts/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use client';

import { createContext, useState } from 'react';

interface User {
is_anonymous: boolean;
access?: string;
first_name?: string;
email?: string;
}

export const defaultUser: User = {
is_anonymous: true,
};

interface UserContextType {
user: User;
setUser: React.Dispatch<React.SetStateAction<User>>;
}

interface UserContextProviderProps {
children: React.ReactNode;
}

export const UserContext = createContext({} as UserContextType);

export default function UserContextProvider({ children, ...props }: UserContextProviderProps) {
const [user, setUser] = useState<User>(defaultUser);

return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
}
106 changes: 4 additions & 102 deletions web/app/globals.css
Original file line number Diff line number Diff line change
@@ -1,107 +1,9 @@
:root {
--max-width: 1100px;
--border-radius: 12px;
--font-mono: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono',
'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro',
'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;

--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;

--primary-glow: conic-gradient(
from 180deg at 50% 50%,
#16abff33 0deg,
#0885ff33 55deg,
#54d6ff33 120deg,
#0071ff33 160deg,
transparent 360deg
);
--secondary-glow: radial-gradient(
rgba(255, 255, 255, 1),
rgba(255, 255, 255, 0)
);

--tile-start-rgb: 239, 245, 249;
--tile-end-rgb: 228, 232, 233;
--tile-border: conic-gradient(
#00000080,
#00000040,
#00000030,
#00000020,
#00000010,
#00000010,
#00000080
);

--callout-rgb: 238, 240, 241;
--callout-border-rgb: 172, 175, 176;
--card-rgb: 180, 185, 188;
--card-border-rgb: 131, 134, 135;
}

@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;

--primary-glow: radial-gradient(rgba(1, 65, 255, 0.4), rgba(1, 65, 255, 0));
--secondary-glow: linear-gradient(
to bottom right,
rgba(1, 65, 255, 0),
rgba(1, 65, 255, 0),
rgba(1, 65, 255, 0.3)
);

--tile-start-rgb: 2, 13, 46;
--tile-end-rgb: 2, 5, 19;
--tile-border: conic-gradient(
#ffffff80,
#ffffff40,
#ffffff30,
#ffffff20,
#ffffff10,
#ffffff10,
#ffffff80
);

--callout-rgb: 20, 20, 20;
--callout-border-rgb: 108, 108, 108;
--card-rgb: 100, 100, 100;
--card-border-rgb: 200, 200, 200;
}
}
@tailwind base;
@tailwind components;
@tailwind utilities;

* {
box-sizing: border-box;
padding: 0;
margin: 0;
}

html,
body {
max-width: 100vw;
overflow-x: hidden;
}

body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}

a {
color: inherit;
text-decoration: none;
}

@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
}
}
10 changes: 10 additions & 0 deletions web/app/hooks/useUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use client';

import { useContext } from 'react';
import { UserContext } from '../contexts/UserContext';

export default function useUser() {
const value = useContext(UserContext);

return value;
}
Loading