|
| 1 | +import { useState, useCallback } from 'react' |
| 2 | +import styles from '~/styles/UserBanner.module.css' |
| 3 | +import { apiClient } from '~/utils/apiClient' |
| 4 | +import type { UserInfo } from '$/types' |
| 5 | +import type { ChangeEvent } from 'react' |
| 6 | + |
| 7 | +const UserBanner = () => { |
| 8 | + const [isLoggedIn, setIsLoggedIn] = useState(false) |
| 9 | + const [token, setToken] = useState('') |
| 10 | + const [userInfo, setUserInfo] = useState({} as UserInfo) |
| 11 | + |
| 12 | + const editIcon = useCallback( |
| 13 | + async (e: ChangeEvent<HTMLInputElement>) => { |
| 14 | + if (!e.target.files?.length) return |
| 15 | + |
| 16 | + setUserInfo( |
| 17 | + await apiClient.user.$post({ |
| 18 | + headers: { authorization: token }, |
| 19 | + body: { icon: e.target.files[0] } |
| 20 | + }) |
| 21 | + ) |
| 22 | + }, |
| 23 | + [token] |
| 24 | + ) |
| 25 | + |
| 26 | + const login = useCallback(async () => { |
| 27 | + const id = prompt('Enter the user id (See server/.env)') |
| 28 | + const pass = prompt('Enter the user pass (See server/.env)') |
| 29 | + if (!id || !pass) return alert('Login failed') |
| 30 | + |
| 31 | + let newToken = '' |
| 32 | + |
| 33 | + try { |
| 34 | + newToken = `Bearer ${ |
| 35 | + (await apiClient.token.$post({ body: { id, pass } })).token |
| 36 | + }` |
| 37 | + setToken(newToken) |
| 38 | + } catch (e) { |
| 39 | + return alert('Login failed') |
| 40 | + } |
| 41 | + |
| 42 | + setUserInfo( |
| 43 | + await apiClient.user.$get({ headers: { authorization: newToken } }) |
| 44 | + ) |
| 45 | + setIsLoggedIn(true) |
| 46 | + }, []) |
| 47 | + |
| 48 | + const logout = useCallback(() => { |
| 49 | + setToken('') |
| 50 | + setIsLoggedIn(false) |
| 51 | + }, []) |
| 52 | + |
| 53 | + return ( |
| 54 | + <div className={styles.userBanner}> |
| 55 | + {isLoggedIn ? ( |
| 56 | + <> |
| 57 | + <img src={userInfo.icon} className={styles.userIcon} /> |
| 58 | + <span>{userInfo.name}</span> |
| 59 | + <input type="file" accept="image/*" onChange={editIcon} /> |
| 60 | + <button onClick={logout}>LOGOUT</button> |
| 61 | + </> |
| 62 | + ) : ( |
| 63 | + <button onClick={login}>LOGIN</button> |
| 64 | + )} |
| 65 | + </div> |
| 66 | + ) |
| 67 | +} |
| 68 | + |
| 69 | +export default UserBanner |
0 commit comments