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 { Icon, Label, NativeTabs } from "expo-router/unstable-native-tabs";
import React from "react"; 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() { export default function TabsLayout() {
return ( return (
@@ -36,13 +15,3 @@ export default function TabsLayout() {
</NativeTabs> </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 { Stack, useRouter, useSegments } from 'expo-router';
import { Text, TouchableOpacity } from 'react-native'; import { Text, TouchableOpacity } from 'react-native';
import { useColorScheme } from '../hooks/use-color-scheme'; import { useColorScheme } from '../hooks/use-color-scheme';
import { AuthProvider } from '../src/context/AuthContext'; import { AuthProvider, useAuth } from '../src/context/AuthContext';
function DevicesHeader() { function DevicesHeader() {
const router = useRouter(); const router = useRouter();
const isDark = useColorScheme() === 'dark'; const isDark = useColorScheme() === 'dark';
const activityColor = isDark ? '#0A84FF' : '#007AFF'; const activityColor = isDark ? '#0A84FF' : '#007AFF';
const { canCreate } = useAuth();
return ( return (
<TouchableOpacity <TouchableOpacity
onPress={() => router.push('/scan-devices')} onPress={() => router.push('/scan-devices')}
disabled={!canCreate}
style={{ paddingHorizontal: 8 }} style={{ paddingHorizontal: 8 }}
> >
<Ionicons name="add-circle-outline" size={24} color={activityColor} /> <Ionicons name="add-circle-outline" size={24} color={canCreate ? activityColor : 'gray'} />
</TouchableOpacity> </TouchableOpacity>
); );
} }

View File

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

View File

@@ -1,256 +1,287 @@
import { Device, AuthResponse, NetworkScanResult } from "../types"; import {
Device,
AuthResponse,
NetworkScanResult,
PermissionResponse,
} from '../types';
class UpSnapAPI { class UpSnapAPI {
private token: string | null = null; private token: string | null = null;
private address: string | null = null; private address: string | null = null;
private canCreate: boolean | null = null;
setToken(token: string) { setToken(token: string) {
this.token = token; this.token = token;
} }
getToken(): string | null { getToken(): string | null {
return this.token; return this.token;
} }
clearToken() { clearToken() {
this.token = null; this.token = null;
} }
setAddress(address: string) { setAddress(address: string) {
this.address = address; this.address = address;
} }
getAddress(): string | null { getAddress(): string | null {
return this.address; return this.address;
} }
clearAddress() { clearAddress() {
this.address = null; this.address = null;
} }
private getHeaders(): HeadersInit { setCanCreate(canCreate: boolean) {
const headers: HeadersInit = { this.canCreate = canCreate;
"Content-Type": "application/json", }
};
if (this.token) { getCanCreate(): boolean | null {
headers["Authorization"] = `Bearer ${this.token}`; return this.canCreate;
} }
return headers; clearCanCreate() {
} this.canCreate = null;
}
async authenticate( private getHeaders(): HeadersInit {
serverAddress: string, const headers: HeadersInit = {
identity: string, 'Content-Type': 'application/json',
password: string };
): Promise<AuthResponse> {
this.address = serverAddress + "/api";
const response = await fetch( if (this.token) {
`${this.address}/collections/users/auth-with-password`, headers['Authorization'] = `Bearer ${this.token}`;
{ }
method: "POST",
headers: this.getHeaders(),
body: JSON.stringify({ identity, password }),
}
);
if (!response.ok) { return headers;
const response = await fetch( }
`${this.address}/collections/_superusers/auth-with-password`,
{
method: "POST",
headers: this.getHeaders(),
body: JSON.stringify({ identity, password }),
}
);
if (!response.ok) { async authenticate(
const error = await response.json(); serverAddress: string,
throw new Error(error.message || "Authentication failed"); identity: string,
} password: string
): Promise<AuthResponse> {
this.address = serverAddress + '/api';
const data: AuthResponse = await response.json(); const response = await fetch(
this.token = data.token; `${this.address}/collections/users/auth-with-password`,
return data; {
} method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify({ identity, password }),
}
);
const data: AuthResponse = await response.json(); if (!response.ok) {
this.token = data.token; const response = await fetch(
return data; `${this.address}/collections/_superusers/auth-with-password`,
} {
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify({ identity, password }),
}
);
async getDevices(page = 1, perPage = 100): Promise<Device[]> { if (!response.ok) {
const response = await fetch( const error = await response.json();
`${this.address}/collections/devices/records?page=${page}&perPage=${perPage}`, throw new Error(error.message || 'Authentication failed');
{ }
headers: this.getHeaders(),
}
);
if (!response.ok) { const data: AuthResponse = await response.json();
throw new Error("Failed to fetch devices"); this.token = data.token;
} this.canCreate = true;
return data;
}
const data = await response.json(); const data: AuthResponse = await response.json();
return data.items; this.token = data.token;
}
async getDevice(id: string): Promise<Device> { const userID = data.record.id;
const response = await fetch( const userPermissionResponse = await fetch(
`${this.address}/collections/devices/records/${id}`, `${this.address}/collections/permissions/records/${userID}?expand=user,read,update,delete,power`,
{ {
headers: this.getHeaders(), headers: this.getHeaders(),
} }
); );
if (!response.ok) { const user: PermissionResponse = await userPermissionResponse.json();
throw new Error("Failed to fetch device"); this.canCreate = user.create;
}
return response.json(); return data;
} }
async createDevice(device: Partial<Device>): Promise<Device> { async getDevices(page = 1, perPage = 100): Promise<Device[]> {
const response = await fetch( const response = await fetch(
`${this.address}/collections/devices/records`, `${this.address}/collections/devices/records?page=${page}&perPage=${perPage}`,
{ {
method: "POST", headers: this.getHeaders(),
headers: this.getHeaders(), }
body: JSON.stringify(device), );
}
);
if (!response.ok) { if (!response.ok) {
const error = await response.json(); throw new Error('Failed to fetch devices');
throw new Error(error.message || "Failed to create device"); }
}
return response.json(); const data = await response.json();
} return data.items;
}
async updateDevice(id: string, device: Partial<Device>): Promise<Device> { async getDevice(id: string): Promise<Device> {
const response = await fetch( const response = await fetch(
`${this.address}/collections/devices/records/${id}`, `${this.address}/collections/devices/records/${id}`,
{ {
method: "PATCH", headers: this.getHeaders(),
headers: this.getHeaders(), }
body: JSON.stringify(device), );
}
);
if (!response.ok) { if (!response.ok) {
const error = await response.json(); throw new Error('Failed to fetch device');
throw new Error(error.message || "Failed to update device"); }
}
return response.json(); return response.json();
} }
async deleteDevice(id: string): Promise<void> { async createDevice(device: Partial<Device>): Promise<Device> {
const response = await fetch( const response = await fetch(
`${this.address}/collections/devices/records/${id}`, `${this.address}/collections/devices/records`,
{ {
method: "DELETE", method: 'POST',
headers: this.getHeaders(), headers: this.getHeaders(),
} body: JSON.stringify(device),
); }
);
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to delete device"); const error = await response.json();
} throw new Error(error.message || 'Failed to create device');
} }
async wakeDevice(id: string): Promise<void> { return response.json();
const response = await fetch(`${this.address}/upsnap/wake/${id}`, { }
headers: this.getHeaders(),
});
if (!response.ok) { async updateDevice(id: string, device: Partial<Device>): Promise<Device> {
throw new Error("Failed to wake device"); const response = await fetch(
} `${this.address}/collections/devices/records/${id}`,
} {
method: 'PATCH',
headers: this.getHeaders(),
body: JSON.stringify(device),
}
);
async wakeGroup(id: string): Promise<void> { if (!response.ok) {
const response = await fetch(`${this.address}/upsnap/wakegroup/${id}`, { const error = await response.json();
headers: this.getHeaders(), throw new Error(error.message || 'Failed to update device');
}); }
if (!response.ok) { return response.json();
throw new Error("Failed to wake group"); }
}
}
async sleepDevice(id: string): Promise<void> { async deleteDevice(id: string): Promise<void> {
const response = await fetch(`${this.address}/upsnap/sleep/${id}`, { const response = await fetch(
headers: this.getHeaders(), `${this.address}/collections/devices/records/${id}`,
}); {
method: 'DELETE',
headers: this.getHeaders(),
}
);
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to sleep device"); throw new Error('Failed to delete device');
} }
} }
async rebootDevice(id: string): Promise<void> { async wakeDevice(id: string): Promise<void> {
const response = await fetch(`${this.address}/upsnap/reboot/${id}`, { const response = await fetch(`${this.address}/upsnap/wake/${id}`, {
headers: this.getHeaders(), headers: this.getHeaders(),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to reboot device"); throw new Error('Failed to wake device');
} }
} }
async shutdownDevice(id: string): Promise<void> { async wakeGroup(id: string): Promise<void> {
const response = await fetch(`${this.address}/upsnap/shutdown/${id}`, { const response = await fetch(`${this.address}/upsnap/wakegroup/${id}`, {
headers: this.getHeaders(), headers: this.getHeaders(),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to shutdown device"); throw new Error('Failed to wake group');
} }
} }
async scanNetwork(): Promise<NetworkScanResult[]> { async sleepDevice(id: string): Promise<void> {
const response = await fetch(`${this.address}/upsnap/scan`, { const response = await fetch(`${this.address}/upsnap/sleep/${id}`, {
headers: this.getHeaders(), headers: this.getHeaders(),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to scan network"); throw new Error('Failed to sleep device');
} }
}
const data = await response.json(); async rebootDevice(id: string): Promise<void> {
if (data.devices && Array.isArray(data.devices)) { const response = await fetch(`${this.address}/upsnap/reboot/${id}`, {
return data.devices.map((item: any) => ({ headers: this.getHeaders(),
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)) { if (!response.ok) {
return data.map((item: any) => ({ throw new Error('Failed to reboot device');
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)) { async shutdownDevice(id: string): Promise<void> {
return data.items.map((item: any) => ({ const response = await fetch(`${this.address}/upsnap/shutdown/${id}`, {
name: item.name || item.hostname || "Unknown", headers: this.getHeaders(),
ip: item.ip || item.ip_address || "", });
mac: item.mac || item.mac_address || "",
mac_vendor: item.mac_vendor || "Unknown",
}));
}
return []; if (!response.ok) {
} throw new Error('Failed to shutdown device');
}
}
async scanNetwork(): Promise<NetworkScanResult[]> {
const response = await fetch(`${this.address}/upsnap/scan`, {
headers: this.getHeaders(),
});
if (!response.ok) {
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',
}));
}
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',
}));
}
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',
}));
}
return [];
}
} }
export default new UpSnapAPI(); export default new UpSnapAPI();

View File

@@ -20,6 +20,20 @@ export interface AuthResponse {
record: User; 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 { export interface User {
id: string; id: string;
collectionId: string; collectionId: string;