Skip to content

Commit

Permalink
feat: improve notification flow during authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
= committed Feb 1, 2024
1 parent 722b343 commit 666cdd7
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 14 deletions.
17 changes: 15 additions & 2 deletions src-tauri/src/services/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,43 @@ use tauri_plugin_oauth::{start_with_config, OauthConfig};

#[derive(Deserialize, Serialize, Clone, Debug)]
struct User {
#[serde(rename = "sub")]
#[serde(rename(deserialize = "sub"))]
google_id: String,
name: String,
email: String,
#[serde(rename = "picture")]
#[serde(rename(deserialize = "picture"))]
image: String,
}

#[derive(Serialize, Clone)]
struct LoginPayload {
step: String,
user: Option<User>,
error: Option<String>,
}

impl LoginPayload {
fn default() -> LoginPayload {
LoginPayload {
step: "start".to_owned(),
error: None,
user: None,
}
}

fn from_error(error: &Error) -> LoginPayload {
LoginPayload {
error: Some(error.to_string()),
user: None,
step: "end".to_owned(),
}
}

fn new(user: User) -> LoginPayload {
LoginPayload {
user: Some(user),
error: None,
step: "end".to_owned(),
}
}
}
Expand All @@ -44,6 +55,8 @@ pub fn login(window: Window) -> Result<u16, String> {
));

start_with_config(config, move |url| {
let _ = window.emit("authentication", LoginPayload::default());

let start_position = url.find("access_token=").unwrap_or(0);
let end_position = url.find("&token_type").unwrap_or(url.len());

Expand Down
6 changes: 3 additions & 3 deletions src/components/Sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ export default function SideBar({

return (
<Container>
<Option onClick={login}>
<Option onClick={logged ? undefined : login}>
{logged && (
<ProfileImage src={user.image} alt="Imagem de perfil" />
<ProfileImage src={user?.image} alt="Imagem de perfil" />
)}
{!logged && <FakeImage>A</FakeImage>}
<OptionTitle>{logged ? user.name : 'Anônimo'}</OptionTitle>
<OptionTitle>{logged ? user?.name : 'Anônimo'}</OptionTitle>
</Option>
<Searchbar onTextChange={onSearchTextChange} />
<Option>
Expand Down
4 changes: 3 additions & 1 deletion src/components/Sidebar/styles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export const Option = styled.button`
background-color: transparent;
`;

export const ProfileImage = styled.img`
export const ProfileImage = styled.img.attrs({
referrerPolicy: 'no-referrer'
})`
height: 34px;
aspect-ratio: 1;
border-radius: 20px;
Expand Down
24 changes: 16 additions & 8 deletions src/contexts/authContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
createContext,
useContext,
useEffect,
useRef,
useState
} from 'react';
import { invoke } from '@tauri-apps/api/tauri';
Expand All @@ -12,7 +13,7 @@ import toast from 'react-hot-toast';
import { AuthenticationPayload, User } from '../types';

interface AuthProviderValue {
user: User;
user: User | null;
logged: boolean;
login: () => Promise<void>;
}
Expand All @@ -22,19 +23,17 @@ const context = createContext<AuthProviderValue>({} as AuthProviderValue);
export function AuthProvider({
children
}: PropsWithChildren): React.ReactElement {
const [logged, setLogged] = useState(false);
const [user, setUser] = useState<User>({} as User);
const [user, setUser] = useState<User | null>(null);
const toastRef = useRef<string | undefined>(undefined);

useEffect(() => {
const data = localStorage.getItem('@user');

if (data === null) {
setLogged(false);
return;
}

setUser(JSON.parse(data));
setLogged(true);
}, []);

useEffect(() => {
Expand All @@ -51,8 +50,15 @@ export function AuthProvider({
}, []);

function handleAuthenticationEvents(event: Event<AuthenticationPayload>) {
if (event.payload.step === 'start') {
toastRef.current = toast.loading('Autenticando, por favor aguarde');
return;
}

if (event.payload.error) {
toast.error('Houve uma falha no processo de authenticação');
toast.error('Houve uma falha no processo de authenticação', {
id: toastRef.current
});
toast.error(event.payload.error);
return;
}
Expand All @@ -61,7 +67,9 @@ export function AuthProvider({

setUser(user);
localStorage.setItem('@user', JSON.stringify(user));
toast.success('Usuário authenticado com sucesso');
toast.success('Usuário authenticado com sucesso', {
id: toastRef.current
});
}

async function login() {
Expand All @@ -78,7 +86,7 @@ export function AuthProvider({
}

return (
<context.Provider value={{ user, logged, login }}>
<context.Provider value={{ user, logged: !!user, login }}>
{children}
</context.Provider>
);
Expand Down
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export interface User {
}

export interface AuthenticationPayload {
step: string;
user?: User;
error?: string;
}

0 comments on commit 666cdd7

Please sign in to comment.