Skip to content

Commit

Permalink
feat: add sharing management (#1178) (closes #1000)
Browse files Browse the repository at this point in the history
  • Loading branch information
WeidiDeng committed Dec 24, 2020
1 parent 8faa96f commit 677bce3
Show file tree
Hide file tree
Showing 10 changed files with 210 additions and 3 deletions.
4 changes: 4 additions & 0 deletions frontend/src/api/share.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { fetchURL, fetchJSON, removePrefix } from './utils'

export async function list() {
return fetchJSON('/api/shares')
}

export async function getHash(hash) {
return fetchJSON(`/api/public/share/${hash}`)
}
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,9 @@
"permissions": "Permissions",
"permissionsHelp": "You can set the user to be an administrator or choose the permissions individually. If you select \"Administrator\", all of the other options will be automatically checked. The management of users remains a privilege of an administrator.\n",
"profileSettings": "Profile Settings",
"shareManagement": "Share Management",
"path": "Path",
"shareDuration": "Share Duration",
"ruleExample1": "prevents the access to any dot file (such as .git, .gitignore) in every folder.\n",
"ruleExample2": "blocks the access to the file named Caddyfile on the root of the scope.",
"rules": "Rules",
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/i18n/zh-cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@
"permissions": "权限",
"permissionsHelp": "您可以将该用户设置为管理员,也可以单独选择各项权限。如果选择了“管理员”,则其他的选项会被自动勾上,同时该用户可以管理其他用户。",
"profileSettings": "个人设置",
"shareManagement": "分享管理",
"path": "路径",
"shareDuration": "分享期限",
"ruleExample1": "阻止用户访问所有文件夹下任何以 . 开头的文件(隐藏文件, 例如: .git, .gitignore)。",
"ruleExample2": "阻止用户访问其目录范围的根目录下名为 Caddyfile 的文件。",
"rules": "规则",
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import User from '@/views/settings/User'
import Settings from '@/views/Settings'
import GlobalSettings from '@/views/settings/Global'
import ProfileSettings from '@/views/settings/Profile'
import Shares from '@/views/settings/Shares'
import Error403 from '@/views/errors/403'
import Error404 from '@/views/errors/404'
import Error500 from '@/views/errors/500'
Expand Down Expand Up @@ -67,6 +68,11 @@ const router = new Router({
name: 'Profile Settings',
component: ProfileSettings
},
{
path: '/settings/shares',
name: 'Shares',
component: Shares
},
{
path: '/settings/global',
name: 'Global Settings',
Expand Down
7 changes: 4 additions & 3 deletions frontend/src/views/Settings.vue
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
<template>
<div class="dashboard">
<ul id="nav" v-if="user.perm.admin">
<ul id="nav">
<li :class="{ active: $route.path === '/settings/profile' }"><router-link to="/settings/profile">{{ $t('settings.profileSettings') }}</router-link></li>
<li :class="{ active: $route.path === '/settings/global' }"><router-link to="/settings/global">{{ $t('settings.globalSettings') }}</router-link></li>
<li :class="{ active: $route.path === '/settings/users' }"><router-link to="/settings/users">{{ $t('settings.userManagement') }}</router-link></li>
<li :class="{ active: $route.path === '/settings/shares' }"><router-link to="/settings/shares">{{ $t('settings.shareManagement') }}</router-link></li>
<li v-if="user.perm.admin" :class="{ active: $route.path === '/settings/global' }"><router-link to="/settings/global">{{ $t('settings.globalSettings') }}</router-link></li>
<li v-if="user.perm.admin" :class="{ active: $route.path === '/settings/users' }"><router-link to="/settings/users">{{ $t('settings.userManagement') }}</router-link></li>
</ul>

<router-view></router-view>
Expand Down
98 changes: 98 additions & 0 deletions frontend/src/views/settings/Shares.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<template>
<div class="card">
<div class="card-title">
<h2>{{ $t('settings.shareManagement') }}</h2>
</div>

<div class="card-content full">
<table>
<tr>
<th>{{ $t('settings.path') }}</th>
<th>{{ $t('settings.shareDuration') }}</th>
<th v-if="user.perm.admin">{{ $t('settings.username') }}</th>
<th></th>
<th></th>
</tr>

<tr v-for="link in links" :key="link.hash">
<td><a :href="buildLink(link.hash)" target="_blank">{{ link.path }}</a></td>
<td>
<template v-if="link.expire !== 0">{{ humanTime(link.expire) }}</template>
<template v-else>{{ $t('permanent') }}</template>
</td>
<td v-if="user.perm.admin">{{ link.username }}</td>
<td class="small">
<button class="action"
@click="deleteLink($event, link)"
:aria-label="$t('buttons.delete')"
:title="$t('buttons.delete')"><i class="material-icons">delete</i></button>
</td>
<td class="small">
<button class="action copy-clipboard"
:data-clipboard-text="buildLink(link.hash)"
:aria-label="$t('buttons.copyToClipboard')"
:title="$t('buttons.copyToClipboard')"><i class="material-icons">content_paste</i></button>
</td>
</tr>
</table>
</div>
</div>
</template>

<script>
import { share as api, users } from '@/api'
import moment from 'moment'
import {baseURL} from "@/utils/constants"
import Clipboard from 'clipboard'
import {mapState} from "vuex";
export default {
name: 'shares',
computed: mapState([ 'user' ]),
data: function () {
return {
links: [],
clip: null
}
},
async created () {
try {
let links = await api.list()
if (this.user.perm.admin) {
let userMap = new Map()
for (let user of await users.getAll()) userMap.set(user.id, user.username)
for (let link of links) link.username = userMap.has(link.userID) ? userMap.get(link.userID) : ''
}
this.links = links
} catch (e) {
this.$showError(e)
}
},
mounted() {
this.clip = new Clipboard('.copy-clipboard')
this.clip.on('success', () => {
this.$showSuccess(this.$t('success.linkCopied'))
})
},
beforeDestroy () {
this.clip.destroy()
},
methods: {
deleteLink: async function (event, link) {
event.preventDefault()
try {
await api.remove(link.hash)
this.links = this.links.filter(item => item.hash !== link.hash)
} catch (e) {
this.$showError(e)
}
},
humanTime (time) {
return moment(time * 1000).fromNow()
},
buildLink (hash) {
return `${window.location.origin}${baseURL}/share/${hash}`
}
}
}
</script>
1 change: 1 addition & 0 deletions http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func NewHandler(imgSvc ImgService, fileCache FileCache, store *storage.Storage,
api.PathPrefix("/resources").Handler(monkey(resourcePostPutHandler, "/api/resources")).Methods("PUT")
api.PathPrefix("/resources").Handler(monkey(resourcePatchHandler, "/api/resources")).Methods("PATCH")

api.Path("/shares").Handler(monkey(shareListHandler, "/api/shares")).Methods("GET")
api.PathPrefix("/share").Handler(monkey(shareGetsHandler, "/api/share")).Methods("GET")
api.PathPrefix("/share").Handler(monkey(sharePostHandler, "/api/share")).Methods("POST")
api.PathPrefix("/share").Handler(monkey(shareDeleteHandler, "/api/share")).Methods("DELETE")
Expand Down
29 changes: 29 additions & 0 deletions http/share.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/base64"
"net/http"
"path"
"sort"
"strconv"
"strings"
"time"
Expand All @@ -23,6 +24,34 @@ func withPermShare(fn handleFunc) handleFunc {
})
}

var shareListHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
var (
s []*share.Link
err error
)
if d.user.Perm.Admin {
s, err = d.store.Share.All()
} else {
s, err = d.store.Share.FindByUserID(d.user.ID)
}
if err == errors.ErrNotExist {
return renderJSON(w, r, []*share.Link{})
}

if err != nil {
return http.StatusInternalServerError, err
}

sort.Slice(s, func(i, j int) bool {
if s[i].UserID != s[j].UserID {
return s[i].UserID < s[j].UserID
}
return s[i].Expire < s[j].Expire
})

return renderJSON(w, r, s)
})

var shareGetsHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
s, err := d.store.Share.Gets(r.URL.Path, d.user.ID)
if err == errors.ErrNotExist {
Expand Down
42 changes: 42 additions & 0 deletions share/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (

// StorageBackend is the interface to implement for a share storage.
type StorageBackend interface {
All() ([]*Link, error)
FindByUserID(id uint) ([]*Link, error)
GetByHash(hash string) (*Link, error)
GetPermanent(path string, id uint) (*Link, error)
Gets(path string, id uint) ([]*Link, error)
Expand All @@ -25,6 +27,46 @@ func NewStorage(back StorageBackend) *Storage {
return &Storage{back: back}
}

// All wraps a StorageBackend.All.
func (s *Storage) All() ([]*Link, error) {
links, err := s.back.All()

if err != nil {
return nil, err
}

for i, link := range links {
if link.Expire != 0 && link.Expire <= time.Now().Unix() {
if err := s.Delete(link.Hash); err != nil {
return nil, err
}
links = append(links[:i], links[i+1:]...)
}
}

return links, nil
}

// FindByUserID wraps a StorageBackend.FindByUserID.
func (s *Storage) FindByUserID(id uint) ([]*Link, error) {
links, err := s.back.FindByUserID(id)

if err != nil {
return nil, err
}

for i, link := range links {
if link.Expire != 0 && link.Expire <= time.Now().Unix() {
if err := s.Delete(link.Hash); err != nil {
return nil, err
}
links = append(links[:i], links[i+1:]...)
}
}

return links, nil
}

// GetByHash wraps a StorageBackend.GetByHash.
func (s *Storage) GetByHash(hash string) (*Link, error) {
link, err := s.back.GetByHash(hash)
Expand Down
20 changes: 20 additions & 0 deletions storage/bolt/share.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@ type shareBackend struct {
db *storm.DB
}

func (s shareBackend) All() ([]*share.Link, error) {
var v []*share.Link
err := s.db.All(&v)
if err == storm.ErrNotFound {
return v, errors.ErrNotExist
}

return v, err
}

func (s shareBackend) FindByUserID(id uint) ([]*share.Link, error) {
var v []*share.Link
err := s.db.Select(q.Eq("UserID", id)).Find(&v)
if err == storm.ErrNotFound {
return v, errors.ErrNotExist
}

return v, err
}

func (s shareBackend) GetByHash(hash string) (*share.Link, error) {
var v share.Link
err := s.db.One("Hash", hash, &v)
Expand Down

0 comments on commit 677bce3

Please sign in to comment.