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"`
} }
+7 -2
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 {
if err != gorm.ErrRecordNotFound { //if record not found, assume user is guest
return []models.Album{}, err return []models.Album{}, err
} }
}
accessLevel, err := CheckUserAlbumAccess(userID, parentID) accessLevel, err := CheckUserAlbumAccess(userID, parentID)
if err != nil { if err != nil {
if err != gorm.ErrRecordNotFound { //if record not found, assume user is guest
return []models.Album{}, err return []models.Album{}, err
} }
if accessLevel < 1 { 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
} }
+15 -21
View File
@@ -11,36 +11,23 @@ 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()
useEffect(() => {
let ignore = false;
const getAlbums = async () => { const getAlbums = async () => {
console.log('Getting albums in parent', currentAlbumName) console.log('Getting albums in parent', currentAlbumName)
if (currentAlbumName === 'gallery') { // Root album const parentId = currentAlbumName === 'gallery' ? "" : currentAlbumName;
try {
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, { const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': getAccessToken(), 'Authorization': getAccessToken(),
}, },
body: JSON.stringify({ body: JSON.stringify({
parentId: "", parentId: parentId,
}),
})
const data = await response.json()
if (data.error) {
setAlbums([])
showError('Failed to get albums')
} else {
setAlbums(data)
}
} else {
const response = await fetch(`${getServerUrl()}/api/albums/getAlbumsInParent`, {
method: 'POST',
headers: {
'Authorization': getAccessToken(),
},
body: JSON.stringify({
parentId: currentAlbumName,
}), }),
}) })
const data = await response.json() const data = await response.json()
if (!ignore) {
if (data.error) { if (data.error) {
setAlbums([]) setAlbums([])
showError('Failed to get albums') showError('Failed to get albums')
@@ -48,11 +35,18 @@ export default function AlbumList({ currentAlbumName }) {
setAlbums(data) setAlbums(data)
} }
} }
} catch (error) {
if (!ignore) {
setAlbums([])
showError('Failed to get albums')
} }
useEffect(() => { }
if (!open) { }
if (!open && currentAlbumName !== null) {
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()