fix: check for create permissions

This commit is contained in:
2026-01-12 21:09:30 -05:00
Unverified
parent 66eb67ad49
commit 8d42dde9b2
5 changed files with 265 additions and 239 deletions

View File

@@ -1,26 +1,5 @@
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { Icon, Label, NativeTabs } from "expo-router/unstable-native-tabs";
import React from "react";
import { StyleSheet, TouchableOpacity, View } from "react-native";
import { useColorScheme } from "../../hooks/use-color-scheme";
export function DevicesHeader() {
const router = useRouter();
const isDark = useColorScheme() === "dark";
const activityColor = isDark ? "#0A84FF" : "#007AFF";
return (
<View style={styles.headerRight}>
<TouchableOpacity
onPress={() => router.push("/scan-devices")}
style={styles.headerButton}
>
<Ionicons name="add-circle-outline" size={24} color={activityColor} />
</TouchableOpacity>
</View>
);
}
export default function TabsLayout() {
return (
@@ -36,13 +15,3 @@ export default function TabsLayout() {
</NativeTabs>
);
}
const styles = StyleSheet.create({
headerRight: {
flexDirection: "row",
gap: 16,
},
headerButton: {
paddingHorizontal: 8,
},
});

View File

@@ -2,19 +2,21 @@ import { Ionicons } from '@expo/vector-icons';
import { Stack, useRouter, useSegments } from 'expo-router';
import { Text, TouchableOpacity } from 'react-native';
import { useColorScheme } from '../hooks/use-color-scheme';
import { AuthProvider } from '../src/context/AuthContext';
import { AuthProvider, useAuth } from '../src/context/AuthContext';
function DevicesHeader() {
const router = useRouter();
const isDark = useColorScheme() === 'dark';
const activityColor = isDark ? '#0A84FF' : '#007AFF';
const { canCreate } = useAuth();
return (
<TouchableOpacity
onPress={() => router.push('/scan-devices')}
disabled={!canCreate}
style={{ paddingHorizontal: 8 }}
>
<Ionicons name="add-circle-outline" size={24} color={activityColor} />
<Ionicons name="add-circle-outline" size={24} color={canCreate ? activityColor : 'gray'} />
</TouchableOpacity>
);
}

View File

@@ -9,6 +9,7 @@ interface AuthContextType {
token: string | null;
isAuthenticated: boolean;
isLoading: boolean;
canCreate: boolean;
login: (serverAddress: string, identity: string, password: string) => Promise<void>;
logout: () => Promise<void>;
}
@@ -20,6 +21,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const [serverAddress, setServerAddress] = useState<string | null>(null);
const [token, setToken] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [canCreate, setCanCreate] = useState<boolean>(false);
useEffect(() => {
loadAuth();
@@ -30,6 +32,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const storedToken = await AsyncStorage.getItem('auth_token');
const storedUser = await AsyncStorage.getItem('auth_user');
const storedServerAddress = await AsyncStorage.getItem('auth_server_address');
const storedCanCreate = await AsyncStorage.getItem('auth_can_create');
if (storedCanCreate) {
setCanCreate(storedCanCreate === 'true');
}
if (storedToken && storedUser) {
setToken(storedToken);
@@ -55,10 +62,12 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
await AsyncStorage.setItem('auth_token', response.token);
await AsyncStorage.setItem('auth_user', JSON.stringify(response.record));
await AsyncStorage.setItem('auth_server_address', serverAddress);
await AsyncStorage.setItem('auth_can_create', api.getCanCreate() ? 'true' : 'false');
setToken(response.token);
setUser(response.record);
setServerAddress(serverAddress);
setCanCreate(api.getCanCreate() || false);
} catch (error) {
throw error;
}
@@ -87,6 +96,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
token,
isAuthenticated: !!token && !!user,
isLoading,
canCreate,
login,
logout,
}}

View File

@@ -1,8 +1,14 @@
import { Device, AuthResponse, NetworkScanResult } from "../types";
import {
Device,
AuthResponse,
NetworkScanResult,
PermissionResponse,
} from '../types';
class UpSnapAPI {
private token: string | null = null;
private address: string | null = null;
private canCreate: boolean | null = null;
setToken(token: string) {
this.token = token;
@@ -28,13 +34,25 @@ class UpSnapAPI {
this.address = null;
}
setCanCreate(canCreate: boolean) {
this.canCreate = canCreate;
}
getCanCreate(): boolean | null {
return this.canCreate;
}
clearCanCreate() {
this.canCreate = null;
}
private getHeaders(): HeadersInit {
const headers: HeadersInit = {
"Content-Type": "application/json",
'Content-Type': 'application/json',
};
if (this.token) {
headers["Authorization"] = `Bearer ${this.token}`;
headers['Authorization'] = `Bearer ${this.token}`;
}
return headers;
@@ -45,12 +63,12 @@ class UpSnapAPI {
identity: string,
password: string
): Promise<AuthResponse> {
this.address = serverAddress + "/api";
this.address = serverAddress + '/api';
const response = await fetch(
`${this.address}/collections/users/auth-with-password`,
{
method: "POST",
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify({ identity, password }),
}
@@ -60,7 +78,7 @@ class UpSnapAPI {
const response = await fetch(
`${this.address}/collections/_superusers/auth-with-password`,
{
method: "POST",
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify({ identity, password }),
}
@@ -68,16 +86,29 @@ class UpSnapAPI {
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || "Authentication failed");
throw new Error(error.message || 'Authentication failed');
}
const data: AuthResponse = await response.json();
this.token = data.token;
this.canCreate = true;
return data;
}
const data: AuthResponse = await response.json();
this.token = data.token;
const userID = data.record.id;
const userPermissionResponse = await fetch(
`${this.address}/collections/permissions/records/${userID}?expand=user,read,update,delete,power`,
{
headers: this.getHeaders(),
}
);
const user: PermissionResponse = await userPermissionResponse.json();
this.canCreate = user.create;
return data;
}
@@ -90,7 +121,7 @@ class UpSnapAPI {
);
if (!response.ok) {
throw new Error("Failed to fetch devices");
throw new Error('Failed to fetch devices');
}
const data = await response.json();
@@ -106,7 +137,7 @@ class UpSnapAPI {
);
if (!response.ok) {
throw new Error("Failed to fetch device");
throw new Error('Failed to fetch device');
}
return response.json();
@@ -116,7 +147,7 @@ class UpSnapAPI {
const response = await fetch(
`${this.address}/collections/devices/records`,
{
method: "POST",
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify(device),
}
@@ -124,7 +155,7 @@ class UpSnapAPI {
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || "Failed to create device");
throw new Error(error.message || 'Failed to create device');
}
return response.json();
@@ -134,7 +165,7 @@ class UpSnapAPI {
const response = await fetch(
`${this.address}/collections/devices/records/${id}`,
{
method: "PATCH",
method: 'PATCH',
headers: this.getHeaders(),
body: JSON.stringify(device),
}
@@ -142,7 +173,7 @@ class UpSnapAPI {
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || "Failed to update device");
throw new Error(error.message || 'Failed to update device');
}
return response.json();
@@ -152,13 +183,13 @@ class UpSnapAPI {
const response = await fetch(
`${this.address}/collections/devices/records/${id}`,
{
method: "DELETE",
method: 'DELETE',
headers: this.getHeaders(),
}
);
if (!response.ok) {
throw new Error("Failed to delete device");
throw new Error('Failed to delete device');
}
}
@@ -168,7 +199,7 @@ class UpSnapAPI {
});
if (!response.ok) {
throw new Error("Failed to wake device");
throw new Error('Failed to wake device');
}
}
@@ -178,7 +209,7 @@ class UpSnapAPI {
});
if (!response.ok) {
throw new Error("Failed to wake group");
throw new Error('Failed to wake group');
}
}
@@ -188,7 +219,7 @@ class UpSnapAPI {
});
if (!response.ok) {
throw new Error("Failed to sleep device");
throw new Error('Failed to sleep device');
}
}
@@ -198,7 +229,7 @@ class UpSnapAPI {
});
if (!response.ok) {
throw new Error("Failed to reboot device");
throw new Error('Failed to reboot device');
}
}
@@ -208,7 +239,7 @@ class UpSnapAPI {
});
if (!response.ok) {
throw new Error("Failed to shutdown device");
throw new Error('Failed to shutdown device');
}
}
@@ -218,34 +249,34 @@ class UpSnapAPI {
});
if (!response.ok) {
throw new Error("Failed to scan network");
throw new Error('Failed to scan network');
}
const data = await response.json();
if (data.devices && Array.isArray(data.devices)) {
return data.devices.map((item: any) => ({
name: item.name || item.hostname || "Unknown",
ip: item.ip || item.ip_address || "",
mac: item.mac || item.mac_address || "",
mac_vendor: item.mac_vendor || "Unknown",
name: item.name || item.hostname || 'Unknown',
ip: item.ip || item.ip_address || '',
mac: item.mac || item.mac_address || '',
mac_vendor: item.mac_vendor || 'Unknown',
}));
}
if (Array.isArray(data)) {
return data.map((item: any) => ({
name: item.name || item.hostname || "Unknown",
ip: item.ip || item.ip_address || "",
mac: item.mac || item.mac_address || "",
mac_vendor: item.mac_vendor || "Unknown",
name: item.name || item.hostname || 'Unknown',
ip: item.ip || item.ip_address || '',
mac: item.mac || item.mac_address || '',
mac_vendor: item.mac_vendor || 'Unknown',
}));
}
if (data.items && Array.isArray(data.items)) {
return data.items.map((item: any) => ({
name: item.name || item.hostname || "Unknown",
ip: item.ip || item.ip_address || "",
mac: item.mac || item.mac_address || "",
mac_vendor: item.mac_vendor || "Unknown",
name: item.name || item.hostname || 'Unknown',
ip: item.ip || item.ip_address || '',
mac: item.mac || item.mac_address || '',
mac_vendor: item.mac_vendor || 'Unknown',
}));
}

View File

@@ -20,6 +20,20 @@ export interface AuthResponse {
record: User;
}
export interface PermissionResponse {
id: string;
collectionId: string;
collectionName: string;
user: User;
create: boolean;
read: Device[];
update: Device[];
delete: Device[];
power: Device[];
created: string;
updated: string;
}
export interface User {
id: string;
collectionId: string;