Fix upload 422, login navigation, and implement admin song moderation

This commit is contained in:
Mikan
2026-11-23 03:17:13 +04:00
parent d746167c66
commit e08954ffc5
7 changed files with 144 additions and 41 deletions

View File

@@ -77,7 +77,7 @@ async def login(data: dict, session: Session = Depends(get_session)):
if not user or not verify_password(data.get("password"), user.hashed_password):
raise HTTPException(status_code=401, detail="Invalid credentials")
return {"access_token": create_access_token({"sub": user.username}), "token_type": "bearer"}
return {"access_token": create_access_token({"sub": user.username}), "token_type": "bearer", "role": user.role}
@router.put("/change-password")
async def change_password(data: PasswordChange, user=Depends(get_current_user), session: Session = Depends(get_session)):

View File

@@ -23,7 +23,7 @@ export default function AppNavigator() {
const token = useAuthStore((state) => state.token);
const linking = {
prefixes: ['http://localhost:8081'],
prefixes: ['http://localhost:8081', 'http://127.0.0.1:8081'],
config: {
screens: {
Login: '',

View File

@@ -1,19 +1,20 @@
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Alert, ScrollView } from 'react-native';
import api from '../api/client';
import { useAuthStore } from '../store/authStore';
export default function AdminPanelScreen() {
const user = useAuthStore((state) => state.user);
const [users, setUsers] = useState([]);
const [pendingSongs, setPendingSongs] = useState([]);
useEffect(() => {
fetchUsers();
fetchPendingSongs();
}, []);
const fetchUsers = async () => {
try {
// Assuming there's an endpoint /admin/users as per plan
const response = await api.get('/admin/users');
setUsers(response.data);
} catch (error) {
@@ -21,6 +22,15 @@ export default function AdminPanelScreen() {
}
};
const fetchPendingSongs = async () => {
try {
const response = await api.get('/admin/moderation');
setPendingSongs(response.data);
} catch (error) {
console.error('Error fetching pending songs:', error);
}
};
const deleteUser = async (userId: number) => {
Alert.alert('Confirm', 'Are you sure you want to delete this user?', [
{ text: 'Cancel', style: 'cancel' },
@@ -40,6 +50,21 @@ export default function AdminPanelScreen() {
]);
};
const handleSongAction = async (songId: number, action: 'approve' | 'reject') => {
try {
if (action === 'approve') {
await api.post(`/admin/moderation/${songId}/approve`);
Alert.alert('Success', 'Song approved');
} else {
await api.delete(`/admin/moderation/${songId}/reject`);
Alert.alert('Success', 'Song rejected');
}
fetchPendingSongs();
} catch (error) {
Alert.alert('Error', `Failed to ${action} song`);
}
};
if (user?.role !== 'admin') {
return (
<View style={styles.container}>
@@ -48,34 +73,65 @@ export default function AdminPanelScreen() {
);
}
const renderItem = ({ item }) => (
<View style={styles.userItem}>
const renderUserItem = ({ item }) => (
<View style={styles.item}>
<View>
<Text style={styles.userName}>{item.username}</Text>
<Text style={styles.itemName}>{item.username}</Text>
<Text>{item.email} - {item.role}</Text>
</View>
<TouchableOpacity onPress={() => deleteUser(item.id)} style={styles.deleteButton}>
<TouchableOpacity onPress={() => deleteUser(item.id)} style={[styles.actionButton, styles.deleteButton]}>
<Text style={{ color: 'white' }}>Delete</Text>
</TouchableOpacity>
</View>
);
const renderSongItem = ({ item }) => (
<View style={styles.item}>
<View>
<Text style={styles.itemName}>{item.title}</Text>
<Text>{item.genre} | Author: {item.author_id}</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={() => handleSongAction(item.id, 'approve')} style={[styles.actionButton, styles.approveButton]}>
<Text style={{ color: 'white' }}>Approve</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => handleSongAction(item.id, 'reject')} style={[styles.actionButton, styles.deleteButton]}>
<Text style={{ color: 'white' }}>Reject</Text>
</TouchableOpacity>
</View>
</View>
);
return (
<View style={styles.container}>
<ScrollView contentContainerStyle={styles.container}>
<Text style={styles.title}>Admin Moderation</Text>
<Text style={styles.sectionTitle}>Pending Songs ({pendingSongs.length})</Text>
<FlatList
data={pendingSongs}
keyExtractor={(item) => item.id.toString()}
renderItem={renderSongItem}
scrollEnabled={false}
/>
<View style={{ height: 30 }} />
<Text style={styles.sectionTitle}>User Management</Text>
<FlatList
data={users}
keyExtractor={(item) => item.id.toString()}
renderItem={renderItem}
renderItem={renderUserItem}
scrollEnabled={false}
/>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#f5f5f5', padding: 20 },
container: { flexGrow: 1, backgroundColor: '#f5f5f5', padding: 20 },
title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, textAlign: 'center' },
userItem: {
sectionTitle: { fontSize: 20, fontWeight: 'bold', marginTop: 20, marginBottom: 10 },
item: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
@@ -86,7 +142,9 @@ const styles = StyleSheet.create({
borderWidth: 1,
borderColor: '#ddd'
},
userName: { fontSize: 16, fontWeight: 'bold' },
deleteButton: { backgroundColor: 'red', padding: 8, borderRadius: 5 },
errorText: { textAlign: 'center', marginTop: 50, color: 'red', fontSize: 18 }
itemName: { fontSize: 16, fontWeight: 'bold' },
actionButton: { padding: 8, borderRadius: 5, marginLeft: 5 },
approveButton: { backgroundColor: 'green' },
deleteButton: { backgroundColor: 'red' },
errorText: { textAlign: 'center', marginTop: 50, color: 'red', fontSize: 18 },
});

View File

@@ -16,8 +16,19 @@ export default function LoginScreen({ navigation }) {
password,
});
setAuth({ username }, response.data.access_token);
Alert.alert('Success', 'Logged in successfully!');
setAuth({ username, role: response.data.role }, response.data.access_token);
console.log('User role from API:', response.data.role);
// Small delay to allow AppNavigator to switch stacks based on the new token
setTimeout(() => {
if (response.data.role === 'admin') {
navigation.navigate('AdminPanel');
} else if (response.data.role === 'author') {
navigation.navigate('Upload');
} else {
navigation.navigate('Discovery');
}
}, 100);
} catch (error) {
Alert.alert('Error', 'Login failed');
}
@@ -51,4 +62,4 @@ const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', padding: 20 },
title: { fontSize: 24, fontWeight: 'bold', textAlign: 'center', marginBottom: 20 },
input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 10, borderRadius: 5 },
});
});

View File

@@ -5,15 +5,22 @@ import { useAuthStore } from '../store/authStore';
export default function SettingsScreen({ navigation }) {
const [oldPassword, setOldPassword] = useState('');
const { user } = useAuthStore();
const [newPassword, setNewPassword] = useState('');
const { user, logout } = useAuthStore();
const handlePasswordChange = async () => {
if (!oldPassword || !newPassword) {
Alert.alert('Error', 'Please provide both old and new passwords');
return;
}
try {
await api.put('/auth/change-password', {
old_password: oldPassword,
new_password: 'newpassword123', // In real UI this would be an input
new_password: newPassword,
});
Alert.alert('Success', 'Password changed successfully!');
setOldPassword('');
setNewPassword('');
} catch (error) {
Alert.alert('Error', 'Failed to change password');
}
@@ -35,8 +42,21 @@ export default function SettingsScreen({ navigation }) {
onChangeText={setOldPassword}
secureTextEntry
/>
{/* New password input would go here */}
<TextInput
style={styles.input}
placeholder="New Password"
value={newPassword}
onChangeText={setNewPassword}
secureTextEntry
/>
<Button title="Update Password" onPress={handlePasswordChange} />
<View style={{ marginTop: 30 }}>
<Button title="Logout" color="red" onPress={() => {
logout();
navigation.navigate('Login');
}} />
</View>
</View>
);
}

View File

@@ -3,7 +3,7 @@ import { View, TextInput, Button, StyleSheet, Alert, ScrollView, TouchableOpacit
import * as DocumentPicker from 'expo-document-picker';
import api from '../api/client';
export default function UploadScreen() {
export default function UploadScreen({ navigation }) {
const [title, setTitle] = useState('');
const [genre, setGenre] = useState('');
const [file, setFile] = useState<DocumentPicker.DocumentPickerItem | null>(null);
@@ -29,20 +29,25 @@ export default function UploadScreen() {
formData.append('title', title);
formData.append('genre', genre);
// In Expo, we need to construct the file object correctly for FormData
const uploadFile = {
uri: file.uri,
name: file.name,
type: file.mimeType || 'audio/mpeg',
} as any;
if (typeof window !== 'undefined') {
// Web implementation: fetch the file from URI and convert to Blob
const response = await fetch(file.uri);
const blob = await response.blob();
formData.append('file', blob, file.name);
} else {
// Mobile implementation (Expo)
const uploadFile = {
uri: file.uri,
name: file.name,
type: file.mimeType || 'audio/mpeg',
} as any;
formData.append('file', uploadFile);
}
formData.append('file', uploadFile);
await api.post('/songs/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
await api.post('/songs/upload', formData);
Alert.alert('Success', 'Song uploaded successfully!');
navigation.navigate('Discovery');
setTitle('');
setGenre('');
setFile(null);
@@ -88,4 +93,4 @@ const styles = StyleSheet.create({
alignItems: 'center',
marginBottom: 20
},
});
});

View File

@@ -1,4 +1,5 @@
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
interface AuthState {
user: any | null;
@@ -7,9 +8,17 @@ interface AuthState {
logout: () => void;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
token: null,
setAuth: (user, token) => set({ user, token }),
logout: () => set({ user: null, token: null }),
}));
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
token: null,
setAuth: (user, token) => set({ user, token }),
logout: () => set({ user: null, token: null }),
}),
{
name: 'auth-storage',
storage: createJSONStorage(() => localStorage),
}
)
);