refactor album access logic to handle guest users and improve state initialization in gallery components

This commit is contained in:
wisplite
2025-11-22 23:56:47 -06:00
parent d9bad97a53
commit eb2691af75
4 changed files with 42 additions and 47 deletions
-4
View File
@@ -11,10 +11,6 @@ func RegisterAlbumRoutes(rg *gin.RouterGroup) {
album := rg.Group("/albums") album := rg.Group("/albums")
album.POST("/getAlbumsInParent", func(c *gin.Context) { album.POST("/getAlbumsInParent", func(c *gin.Context) {
accessToken := c.GetHeader("Authorization") accessToken := c.GetHeader("Authorization")
if accessToken == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
var request struct { var request struct {
ParentID string `json:"parentId"` ParentID string `json:"parentId"`
} }
+9 -4
View File
@@ -14,17 +14,22 @@ import (
func GetAlbumsInParent(parentID string, authToken string) ([]models.Album, error) { func GetAlbumsInParent(parentID string, authToken string) ([]models.Album, error) {
userID, err := ValidateAccessToken(authToken) userID, err := ValidateAccessToken(authToken)
if err != nil { if err != nil {
return []models.Album{}, err if err != gorm.ErrRecordNotFound { //if record not found, assume user is guest
return []models.Album{}, err
}
} }
accessLevel, err := CheckUserAlbumAccess(userID, parentID) accessLevel, err := CheckUserAlbumAccess(userID, parentID)
if err != nil { if err != nil {
return []models.Album{}, err if err != gorm.ErrRecordNotFound { //if record not found, assume user is guest
return []models.Album{}, err
}
accessLevel = 1
} }
if accessLevel < 1 { if accessLevel < 0 {
return []models.Album{}, fmt.Errorf("user does not have permission to view albums in this parent") return []models.Album{}, fmt.Errorf("user does not have permission to view albums in this parent")
} }
albums := []models.Album{} albums := []models.Album{}
result := db.GetDB().Where("private = ?", false).Where("parent_id = ?", parentID).Find(&albums) result := db.GetDB().Where("parent_id = ?", parentID).Find(&albums)
if result.Error != nil { if result.Error != nil {
return []models.Album{}, result.Error return []models.Album{}, result.Error
} }
+32 -38
View File
@@ -11,48 +11,42 @@ export default function AlbumList({ currentAlbumName }) {
const [albums, setAlbums] = useState([]) const [albums, setAlbums] = useState([])
const navigate = useNavigate() const navigate = useNavigate()
const { showError } = useNotifier() const { showError } = useNotifier()
const getAlbums = async () => { useEffect(() => {
console.log('Getting albums in parent', currentAlbumName) let ignore = false;
if (currentAlbumName === 'gallery') { // Root album const getAlbums = async () => {
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, { console.log('Getting albums in parent', currentAlbumName)
method: 'POST', const parentId = currentAlbumName === 'gallery' ? "" : currentAlbumName;
headers: { try {
'Authorization': getAccessToken(), const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, {
}, method: 'POST',
body: JSON.stringify({ headers: {
parentId: "", 'Authorization': getAccessToken(),
}), },
}) body: JSON.stringify({
const data = await response.json() parentId: parentId,
if (data.error) { }),
setAlbums([]) })
showError('Failed to get albums') const data = await response.json()
} else { if (!ignore) {
setAlbums(data) if (data.error) {
} setAlbums([])
} else { showError('Failed to get albums')
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, { } else {
method: 'POST', setAlbums(data)
headers: { }
'Authorization': getAccessToken(), }
}, } catch (error) {
body: JSON.stringify({ if (!ignore) {
parentId: currentAlbumName, setAlbums([])
}), showError('Failed to get albums')
}) }
const data = await response.json()
if (data.error) {
setAlbums([])
showError('Failed to get albums')
} else {
setAlbums(data)
} }
} }
}
useEffect(() => { if (!open && currentAlbumName !== null) {
if (!open) {
getAlbums() getAlbums()
} }
return () => { ignore = true; }
}, [currentAlbumName, open]) }, [currentAlbumName, open])
return ( return (
<div className="flex flex-col items-center justify-start h-full w-full bg-[#141414]"> <div className="flex flex-col items-center justify-start h-full w-full bg-[#141414]">
+1 -1
View File
@@ -9,7 +9,7 @@ export default function Gallery() {
const currentPath = useLocation().pathname; const currentPath = useLocation().pathname;
const pathList = currentPath.split('/').slice(1); const pathList = currentPath.split('/').slice(1);
const currentAlbumName = pathList[pathList.length - 1]; const currentAlbumName = pathList[pathList.length - 1];
const [currentAlbumID, setCurrentAlbumID] = useState("!notfound!"); // set to impossible value to prevent client from fetching root album const [currentAlbumID, setCurrentAlbumID] = useState(null); // Initialize as null to prevent premature fetching
const { fetchUserData, user } = useAccount() const { fetchUserData, user } = useAccount()
const { getAccessToken } = useAccount() const { getAccessToken } = useAccount()
const { showError } = useNotifier() const { showError } = useNotifier()